创建基类指针的向量并将派生类对象传递给它(多态性)

Making a vector of base class pointers and pass Derived class objects to it (Polymorphism)

本文关键字:多态性 对象 指针 基类 向量 派生 创建      更新时间:2023-10-16

我正在尝试为我的Shape程序实现一个菜单。我已经实现了所有的形状类。两个直接派生自抽象类"Shape",另外两个派生自一个名为"Polygon"的类,该类派生自"Shape",如下所示:

Shape -> Polygon -> Rectangle, Triangle
`-> Circle, Arrow

在我的菜单类中,我想创建某种数组,该数组可以包含指向对象的指针以及基类"Shape"的类型。但是我不确定如何正确地做到这一点,并且以一种适用于所有形状的方式,因为我的 2 个类不是直接从"Shape"派生的。

这是我的菜单类:

class Menu
{
protected:
//array of derived objects 
public:
Menu();
~Menu();
// more functions..
void addShape(Shape& shape);
void deleteAllShapes();
void deleteShape(Shape& shape);
void printDetails(Shape& shape);
private:
Canvas _canvas; //Ignore, I use this program to eventually draw this objects to a cool GUI
};

在函数"addShape(Shape& shape(;"中,我想用它来将每个给定的形状添加到我的数组中。如何实现向其添加新对象?而且,如何检查给定对象是否派生自"多边形"?因为如果是这样,那么据我所知,我需要以不同的方式调用成员函数。

我看到你在菜单中有一个数组,假设:

Shape* myshapes[10];

形状可以是矩形,三角形,圆形等。 你想要的是能够使用菜单的 printDetails(( 方法,如下所示:

void printDetails()
{
for(int i = 0; i < size; i++)
{
cout << "Index " << i << " has " << myshapes[i]->getShapeName() << endl;
}
}

getShapeName(( 将返回一个字符串,例如,如果它是 Rectangle,则返回 "Rectangle"。 您将能够在纯虚拟功能的帮助下做到这一点。纯虚函数必须在抽象类 Shape 中,它具有:

virtual string getShapeName() = 0; //pure virtual

这意味着我们期待在派生类中对此函数进行定义。这样,您将能够使用shapes数组中的Shape指针使用getShapeName((方法,这将告诉您形状是矩形,三角形还是圆形等。

class Shape
{
public:
virtual string getShapeName() = 0;
};
class Circle : public Shape
{
private:
int radius;
public:
Circle(int r) { radius = r; cout << "Circle created!n"; }
string getShapeName() { return "Circle"; }
};
class Arrow : public Shape
{
private:
int length;
public:
Arrow(int l) { length = l; cout << "Arrow created!n"; }
string getShapeName() { return "Arrow"; }
};
class Polygon : public Shape
{
public:
virtual string getShapeName() = 0;
};
class Triangle : public Polygon
{
private:
int x, y, z;
public:
Triangle(int a, int b, int c) { x = a; y = b; z = c; cout << "Triangle created!n"; }
string getShapeName() { return "Triangle"; }
};
class Rectangle : public Polygon
{
private:
int length;
int width;
public:
Rectangle(int l, int w){ length = l; width = w; cout << "Rectangle created!n"; }
string getShapeName() { return "Rectangle"; }
};

要实现 addShape(( 方法,您可以这样做:

void addShape(Shape &shape)
{
myshapes[count] = &shape;
count++;
}

另外,请记住在 addShape(( 方法中通过引用或使用指针传递 Shape。 我希望这有帮助...祝你好运:-(