如何多态地创建对象的动态数组

How to create a dynamic array of objects polymorphically?

本文关键字:创建对象 动态 数组 何多态 多态      更新时间:2023-10-16

如果我有一个带有派生类的抽象类,并且不使用 STL 数据结构类,我如何多态地创建对象的动态数组?(向量、列表等)

对象的静态数组

TwoDimensionShape *shapes[2];       
shapes[0] = &Triangle("right", 8.0, 12.0);  
shapes[1] = &Rectangle(10);  

我知道我不能这样做,因为您无法创建抽象类的对象:

cin >> x;
TwoDimensionShape *s = new TwoDimensionShape [x];

编辑:

感谢尼克,这有效:

  int x = 5;
  TwoDimensionShape **shapes = new (TwoDimensionShape*[x]);

您可以创建指向该类的指针数组:

TwoDimensionShape **s = new TwoDimensionShape*[x];

然后用它的特定类型构造每个对象:

s[0] = new Triangle("right", 8.0, 12.0);  
s[1] = new Rectangle(10);

类似于你所拥有的。请记住在不再需要时删除。