如何多态地创建对象的动态数组
How to create a dynamic array of objects polymorphically?
如果我有一个带有派生类的抽象类,并且不使用 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);
类似于你所拥有的。请记住在不再需要时删除。
相关文章:
- 有没有办法基于文本文件动态创建对象?
- 如何创建一个动态数组,该数组可以保存从C++中派生的同一基类的所有不同对象
- 创建一个动态2D数组来存储类对象
- 创建对象的动态数组,删除对象并释放C++内存
- 动态创建对象并将其内存设置为 0
- 如何多态地创建对象的动态数组
- 在循环中动态创建对象
- 从QML动态创建C++对象
- 如何创建指向动态分配对象的指针向量
- 存储动态创建对象的列表/向量的最佳方法是什么
- 用c++动态创建对象
- 创建对象的动态数组
- 在 c++ 中动态创建对象
- 如何在不使用默认构造函数的情况下通过new创建对象的动态大小数组
- C++创建对象的动态数组
- 如何创建一个动态分配的c++对象及其指针
- 如何动态创建对象
- 如何在没有动态内存分配的情况下创建对象数组
- c++:在构造函数调用中作为参数创建的动态分配对象会发生什么?
- 在C++中动态创建对象