抽象类实例的动态初始化

dynamic initialization of abstract class instances

本文关键字:初始化 动态 实例 抽象类      更新时间:2023-10-16

假设我有以下

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)