在C ++中初始化抽象基类的子类数组
我在C ++中有一个抽象基类,需要创建一个数组来存储作为其子类的对象.由于数组的每个成员都必须具有相同的大小,因此我使用了指向子类的指针.目前,我正在像这样声明和初始化我的数组:
I have an abstract base class in C++ and need to create an array to store objects which are subclasses of it. I use pointers to the subclasses since each member of the array needs to be of the same size. Currently I am declaring and initializing my array like this:
BaseClass *array[];
...
array =
{
&SubClass1(...),
&SubClass2(...),
...
&SubClass3(...)
};
当我尝试编译时,这给了我以下信息:
This is giving me the following when I try to compile:
warning: taking address of temporary
error: too many initializers for ‘BaseClass* [0]’
执行此操作的正确方法是什么?
What's the proper way of doing this?
与您在& SubClass1()中所做的操作相同,并且不带临时地址...),
.诸如此类的东西:
On the same line and not taking the address of the temporary as you're doing in &SubClass1(...),
. Something, like:
BaseClass *array [] = { new SubClass(...), new SubClass2(...), .... };
但是这种设计有点像不知道如何做工厂.
But this design smells a bit like not knowing how to do a factory.
由于您没有使用 std :: shared_ptr
或 std :: unique_ptr
来管理指针,所以请不要忘记删除
!(感谢@dasblinkenlight)
As you're not using std::shared_ptr
or std::unique_ptr
to manage your pointer, do not forget to delete
them ! (thanks @dasblinkenlight)