抽象类实例的动态初始化
dynamic initialization of abstract class instances
假设我有以下
class Parent {
protected:
virtual void overrideMe() = 0;
}
class ChildA : public Parent {
protected:
void overrideMe() = 0{}
}
class ChildB : public Parent {
protected:
void overrideMe() = 0{}
}
class UtilClass {
public:
vector<Parent> planes;
void compute() {
Parent& p = planes[0];
}
}
在这种情况下,我会在UtilsClass的compute()中得到一个错误,即"Parent"无法初始化。
我想做的是在UtilClass中填充数组"planes"(使用ChildA或childB,即非混合类型)并进行一些计算。
我必须在初始化过程中使用指针,还是更好地使用模板?我几乎可以肯定,模板的使用是不必要的,因为我想限制使用仅限于Parent类的子类。
vector<Parent> planes;
没有意义,因为Parent
不可能存在。这是一个抽象类。你可以有一个指针向量,或者更好的是,智能指针。
即使Parent
不是抽象的,Parent
对象的向量也会受到对象切片的影响,这可能不是您想要的,因为它会破坏多态性。
class UtilClass {
public:
vector<Parent*> planes;
void compute() {
Parent& p = *planes[0];
}
}
您不能有
vector<Parent> planes;
因为Parent类是抽象的,不能实例化。你需要使用类似的东西
vector<Parent*> planes;
相反,如果您想通过使用这种语法创建派生类对象来获得从Parent派生的对象向量
Parent* pNewObject = new ChildB;
planes.push_back(pNewObject)
相关文章:
- 内联映射初始化的动态atexit析构函数崩溃
- 动态初始化 C 与 C++ 中的静态值
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- 静态和动态模板初始化可以交错吗?
- 虚拟成员函数的定义是否强制在同一转换单元中动态初始化静态数据成员?
- C++ - 使用类中的初始值设定项列表初始化动态集
- 异常 尝试初始化动态数组时未处理
- 如何使用initializer_ist在构造函数中初始化动态数组
- 如何在类中初始化动态数组
- 如何使用一些参数初始化动态分配的数组中的对象
- 初始化动态分配的数组时出错
- 使用对象的复制构造函数初始化动态数组对象
- 初始化动态数组
- 通过已存在的对象初始化动态分配的对象
- c++初始化动态内存中c样式字符串的默认值
- 如何在c++中以非标准方式初始化动态内存
- 初始化动态字符串数组(c++)
- 如何使用memset初始化动态二维数组
- 初始化动态向量列表
- 特征:逗号初始化动态矩阵