[英]How do I declare an array of objects within it's own class?
I am unsure how to create an array of objects within its own class. 我不确定如何在自己的类中创建对象数组。 For example:
例如:
class A {
public:
const static int MAX_SIZE = 10;
private:
A arrayOfOBjects[MAX_SIZE];
}
I get an error saying, "incomplete type is now allowed" How would I go about this? 我收到一条错误消息:“现在允许使用不完整的类型”我将如何处理? If I declare an array of objects from another class inside Class A it will work.. But how do I create an array of objects within its own class?
如果我从A类中的另一个类声明一个对象数组,则它将起作用。但是如何在其自己的类中创建对象数组?
use a pointer. 使用指针。 or shared_ptr etc and dynamically allocate the objects
或shared_ptr等,并动态分配对象
class A {
public:
const static int MAX_SIZE = 10;
private:
A * arrayOfOBjects[MAX_SIZE];
}
You obviously can't contain an instance of the object in itself. 很明显,您本身不能包含该对象的实例。 It would take infinite amount of storage ;-)
这将需要无限量的存储;-)
For the same reason you can't contain several. 出于相同的原因,您不能包含多个。 Maybe you meant the array to be a static member that doesn't add to the state of one instance?
也许您是说要使数组成为不增加一个实例状态的静态成员?
By using pointers you can solve this problem 通过使用指针,您可以解决此问题
class A {
public:
const static int MAX_SIZE = 10;
void allocate(){
arrayOfOBjects=new A[MAX_SIZE];
}
private:
A *arrayOfOBjects;
};
You can use this as following 您可以如下使用
A a;
a.allocate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.