繁体   English   中英

如何创建一个动态数组,该数组可以容纳所有不同的对象,这些对象都源自C ++中的同一基类

[英]How to create a dynamic array that can hold different objects all derived from the same base class in C++

我的作业不允许我使用向量类。 我有一个名为Shape的基类,还有其他派生类,如Rectangle和Circle,我必须创建自己的向量类,该向量类具有一个动态数组,可以容纳所有这些不同的形状。 我使用了以下似乎很好用的方法

 int **shape=new int*[capacity];

我的问题来自“ add_shape”函数。 我知道如何使用例如分别添加形状:

shape[0]=new Rectangle();
shape[1]=new Circle();

但是如何创建通用函数来添加形状,例如可以是矩形或圆形。

只是想详细说明Nicky C的评论。

#include <memory>
using namespace std;

class Shape {};
class Rectangle : public Shape {};
class Circle : public Shape {};
template <class Type> class MyVector {}; // implement (with push method, etc.)

int main()
{
    MyVector<unique_ptr<Shape>> v;
    v.push(unique_ptr<Shape>(new Rectangle()));
    v.push(unique_ptr<Shape>(new Circle()));

    return 0;
}

向量包含类型为unique_ptr<Shape>元素,这是基类。 向量的每个元素也可以是unique_ptr<Rectangle>unique_ptr<Circle> 但是,如果向量的类型为unique_ptr<Rectangle> ,则每个元素的类型必须为unique_ptr<Rectangle> (即,其类型不能为unique_ptr<Circle> )。

由于您是在堆上分配内存,因此使用unique_ptr只是确保您不需要自己调用delete

继承/多态性的优点之一是,可以在需要基类的任何地方使用派生类。 这是一个重要的关键概念。 例如,如上面的代码所示,您可以执行以下操作:

Shape *s = new Shape();
s = new Rectangle();
s = new Circle();

这也适用于功能参数:

class DynamicArray
{
   private:
      Shape **_shapes[];
   ...
   public:
      void add_shape(Shape *s)
      {
         // Add the shape to _shapes;
      }
   ...
};

void main()
{
   DynamicArray array;
   array.add_shape(new Shape()):
   array.add_shape(new Rectangle()):
   array.add_shape(new Circle()):
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM