简体   繁体   English

复制构造函数C ++中自定义类的动态数组

[英]Dynamic array of a custom class in a copy constructor C++

I'm trying to create a dynamic array of a class that I created by defining a pointer of this class in my other class, then when I create the copy constructor of the second class the IDE tells me that the pointer type is not compatible 我试图通过在另一个类中定义该类的指针来创建该类的动态数组,然后在创建第二个类的副本构造函数时,IDE告诉我该指针类型不兼容

class myClass2 {
private:
        int *size;
        string name;
        myClass1 *list;
        ...
public:
       myClass2(const char &name,const int size);
       ...
};

myClass2::myClass2(const char &name,const int size){
...
       this->size = new int(size);
       myClass1 * pArray[size]; 
       for(int i = 0; i < size; i++){
           pArray[i] = new myClass1();
       }
       list = pArray; //FIXME:incompatible pointer type
};

You have written: 你写:

myClass1 *list;

It means that list 's value will be address of a myClass1 object. 这意味着list的值将是myClass1对象的地址。 In contructor of myClass2 , you wrote: myClass2构造myClass2 ,您写道:

list = pArray;

But pArray is not an address of a myClass1 object. 但是pArray不是myClass1对象的地址。 your pArray is an array used to contains myClass2* . 您的pArray是用于包含myClass2*的数组。 So you got error incompatible pointer type . 因此,您得到了与incompatible pointer type错误。

You're trying to point to MyClass2 type from MyClass1 type. 您试图从MyClass1类型指向MyClass2类型。 That's why there's an incompatible type error. 这就是为什么存在不兼容的类型错误的原因。 Either extend MyClass1 for MyClass2 and use polymorphism. 为MyClass2扩展MyClass1并使用多态。 Myclass1 * pArray[size];

PS : It is recommended to use the stack for storing variables unless it is not local. PS:建议使用堆栈来存储变量,除非它不是本地的。 You could do, int size; this->size = size; 你可以做的, int size; this->size = size; int size; this->size = size;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM