在C ++中初始化抽象基类的子类数组 [英] Initializing array of subclasses of abstract base class in C++

查看:104
本文介绍了在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)

这篇关于在C ++中初始化抽象基类的子类数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆