1. In this programm, why does constructor has no parameters? Yet it is there to set the array's count to 0. If I understand right, constructor is useful if I have no input function. |
It has no parameters because it doesn't need any. Think about it, which would you rather write when using limset3:
limset3 mySet;
or
limset3 mySet(42);
the first example is easy because there is nothing to remember. You want a limset3? You declare it. You're done.
The constructor has to set the count to zero because in general there is no guarantee that an object will be placed in zero-initialized memory. In other words, the compiler might place the object in memory that has data from previous objects in it. Thus you should always initialize the members in the constructor.
2. Related to 1st question. Do I really don't need any input function here? |
Well, the assignment says that you have to let the user input 3 numbers, so there has to be code for doing that somewhere. Note that the code does NOT have to be in the class itself. The interface to this class is designed so that a program can put numbers in the set regardless of where they came from. That's good class design because it's flexible.
3. Why isn't "int a" given in class private field? |
I assume you mean int a in the
add()
and
contains()
methods. These are parameters to the methods because that makes them easy to use. Again, consider the alternative:
limset3 mySet;
1 2
|
mySet.a = getSomeNumber();
mySet.add();
|
vs
mSet.add(getSomeNumber())
;
Even more important, consider if you wanted to add two numbers and check the result.
1 2 3 4 5 6
|
mySet.a = number1;
bool result1 = mySet.add();
mySet.a = number2;
if (result1 && mySet.add()) {
cout << "It worked\n";
}
|
vs
1 2 3
|
if (mySet.add(number1) && mySet.add(number2)) {
cout << "It worked\n";
}
|
4. If someone could write me int.main() funcion for this programm, would be much appreciated.
It's unlikely that anyone here will write the code for you, but here is some pseudo-code that should help you get started. It uses a for loop and some I/O, which you should be familiar with.
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
limset3 mySet; // here is your limset3 object
for (i = 1 to 3) { // <<---- you will need to write the correct syntax
// print a prompt
// read a number from the user into a variable.
// call mySet.add(number) where "number" is the number gotten from the user.
// If mySet.add() returned false then print a message
}
// call mySet.print() to print the contents of the array.
return 0;
}
|
5. And question unrelated to this programm. About string. How does strcpy differs from strdup? Does strcpy simply copies array and strdup copies it + remembers the place in memory? |
strcpy() copies a c-string from the src to the dst. You supply the src and dst addresses.
strdup() allocates space on the heap and copies the string to the new space. You are then responsible for free()'ing the memory at some later time.