繁体   English   中英

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

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

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

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

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

这是我的菜单类:

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() 将返回一个字符串,例如“矩形”,如果它是矩形。 您将能够在纯虚函数的帮助下做到这一点。 纯虚函数必须在抽象类 Shape 中,它具有:

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

这意味着我们期望在派生类中定义此函数。 通过这种方式,您将能够使用形状数组中的形状指针使用 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。 我希望这会有所帮助...祝你好运:-)

暂无
暂无

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

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