问题
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?
回答1:
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.
As you're not using std::shared_ptr
or std::unique_ptr
to manage your pointer, do not forget to delete
them ! (thanks @dasblinkenlight)
回答2:
You cannot do it with temporaries - you should allocate your objects statically, dynamically, or put them in the automated storage.
To allocate objects statically, do this:
static SubClass1 s1(..);
static SubClass2 s2(..);
static SubClass3 s3(..);
BaseClass *array [] = { &s1, &s2, &s3 };
If you allocate them dynamically, consider using a vector<shared_ptr<T>>
instead of "raw" pointers to automate deallocation:
vector<shared_ptr<BaseClass>> data = {
make_shared<SubClass1>(...)
, make_shared<SubClass2>(...)
, make_shared<SubClass3>(...)
};
回答3:
Those SubClass1(...)
are temporary objects and if the control goes out of the scope they will be destructed and all pointers of array
will be dangling pointer to invalid addresses.
You can make those objects in array
's scope to make sure those objects and this array have same lifetime:
SubClass1 class1 (...);
SubClass2 class2 (...);
SubClass3 class3 (...);
BaseClass *array[] =
{
&class1(...),
&class2(...),
...
};
Also you can use smart pointer:
std::unique_ptr<BaseClass> array[] =
{
std::unique_ptr<BaseClass>(new SubClass1),
std::unique_ptr<BaseClass>(new SubClass2)
};
来源:https://stackoverflow.com/questions/20127889/initializing-array-of-subclasses-of-abstract-base-class-in-c