我的作业不允许我使用矢量类。我有一个名为Shape的基类和不同的派生类,如Rectangle和Circle,我必须创建自己的矢量类,它有一个动态数组,可以容纳所有这些不同的形状。我使用了以下似乎运行良好的方法
int **shape=new int*[capacity];
我的问题来自" add_shape"功能。我知道如何使用例如单独添加形状:
shape[0]=new Rectangle();
shape[1]=new Circle();
但是如何创建一个通用函数来添加一个可以是矩形或圆形的形状。
答案 0 :(得分:2)
只是想详细说明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
。
答案 1 :(得分:0)
继承/多态的一个优点是,无论何处需要基类,都可以使用派生类。这是一个重要的关键概念。例如,与上面的代码一样,您可以执行以下操作:
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()):
}