| lucas2002 (3) | |||||||
|
Hi guys I'm having a little problem in my code, but I don't know how to solve it. I have a class called Myclass. This class have a public var, called Tag, where I save a int number.
Now, in the main function, I creates an array of Myclass, so
later, I assigns a value to each Tag, belonging to each array element
but when I want to print the value of classes[5]->Tag, im getting the address of the value, but no the int number of Tag. I know that I can use an indexer (like, classes[5]->Tag), but I need to access the element in the shown way. Somebody can tell me how can I fix this problem. Thanks in advance | |||||||
|
|
|||||||
| mik2718 (295) | |||
Well I'm confused but you could just create a normal array instead of an array of pointers.
Note: you have malloc(sizeof(Myclass)*100) which is probably going to give you more than 100 pointers (possibly - depends on size of class). should be malloc(sizeof(Myclass*)*100) for an array of 100 pointers. With the normal array you just use classes[i].Tag to get the element (this cannot be used for polymorphic classes) | |||
|
|
|||
| lucas2002 (3) | |
|
Hi mik2718 I have tried with Myclass* classes = (Myclass*)malloc(sizeof(Myclass)*100); but when I make for (int i=0; i < 100; i++) { classes[i] = new MyClass(); classes[i].Tag = i; } I get an error, because I can't use the the class's constructor main.cpp: In function `int main()': main.cpp:46: error: no match for 'operator=' in '*(classes + (+(i * 8))) = (operator new(8), ((true, (<anonymous>->Myclass::Myclass(), (<anonymous> <unknown operator> false))), <anonymous>))' main.cpp:17: error: candidates are: Myclass& Myclass::operator=(const Myclass&) Why I can't use the constructor??? Thanks | |
|
|
|
| kbw (5375) | |||||
Don't do this:
I really can't say this enough, but DO NOT CAST. C++ is all about static type checking that the compiler can do at compile time. The language has a constrained object model just to support this singularly important feature. If you're going start casting, you may as well be using something based on the Smalltalk object model where you have all kinds of run-time benefits. Your print statement should be:
| |||||
|
Last edited on
|
|||||
| mik2718 (295) | |||
If you use new to allocate the array the constructor is called for each object
remember to use delete [] to free the memory where did you get malloc from? | |||
|
|
|||
| lucas2002 (3) | |
|
Hello. But, if the constructor is called for each object, how can I to pass the parameters for the constructor? | |
|
|
|
| kbw (5375) | |||
|
You can't. That use implies the default constructor, but that's what your sample code uses. It's the use of malloc that's the real problem with your code. It's wrong in principle. If could be written as:
| |||
|
Last edited on
|
|||
| ne555 (4042) | |||
| |||
|
|
|||