我有一个名为“Cara”的类,我在其他类中有这个属性:
Cara** caras;
。 caras
是一个指向“Cara”类型对象的指针数组。
我不知道如何声明这个属性。你能救我吗?
答案 0 :(得分:1)
如果您没有报告某种特定错误,很难说出您的问题是什么。但是,它可能会帮助您知道您可以声明一个类:
class Cara; // this is called a "forward declaration"
并允许您引用它:
class Bob { Cara ** caras; };
甚至在你定义它之前:
class Cara { int foo; };
答案 1 :(得分:1)
如果您尝试为Cara
类型的对象分配指针数组,则可以使用:
Cara **caras = new Cara *[numElements];
如果您想要自己分配Cara
个对象,可以使用:
for(int i = 0; i < numElements; ++i)
caras[i] = new Cara;
答案 2 :(得分:1)
不希望使用数组,而是使用std::vector
。
使用std::vector
:
class Cara;
std::vector<Cara *> my_vector_of_pointers;
//...
for (i = 0; i < 10; ++i)
{
my_vector_of_pointers.push_back(new Cara);
}
如果必须使用数组:
#define ARRAY_CAPACITY 10
Cara * my_array_of_pointers[ARRAY_CAPACITY];
另外注意,更喜欢使用智能指针而不是常规指针。在网上搜索“boost smart_ptr”或“boost shared_ptr”。