获取定义为父类的子类以输出子函数



我有一个定义如下的类:

#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class Shape {
protected:
    float width, height;
public:
    virtual ~Shape(){}
    void set_data (float a, float b){
        width = a;
        height = b;
    }
    virtual string getType() {
        return "Shapes";
    }
};
class Polygon: public Shape {
public:
    virtual ~Polygon(){};
    virtual string getType() {
        return "Polygon";
    }
};
class Triangle: public Polygon {
    public:
        virtual ~Triangle(){};
    virtual string getType() {
        return "Triangle";
    }
};

我想得到一个使用这个类的程序

int main () {
    Shape poly = Polygon();
    Shape tri = Triangle();
    std::cout << poly.getType() << std::endl;
    std::cout << tri.getType() << std::endl;
    return 0;
}

例如,有没有办法让poly.getType()打印出Polygon?现在它正在打印出Shapes.我知道我是否做到了

Polygon poly = Polygon()

这就可以了,但我想将poly存储为 Shape 对象,使用 Polygon 构造函数构造它,并确保

poly.getType()

返回Polygon,而不是Shapes

多态性仅适用于非值类型;即引用和指针。而且由于引用必须立即绑定,因此在这里没有多大用处。

最好的办法是使用 std::unique_ptr<Shape> poly(new Polygon()); 并使用

poly->getType();

我正在使用std::unique_ptr,所以我不需要显式调用deletestd::shared_ptr也可以工作,但请查阅文档,以便使用最适合您的用例的文档。

顺便说一下,在子类中重写函数时,您无需重复virtual。您只需在基类中标记函数virtual

您的代码受到对象切片的影响。用:

int main () {
    std::unique_ptr<Shape> poly = new Polygon();
    std::unique_ptr<Shape> tri = new Triangle();
    std::cout << poly->getType() << std::endl;
    std::cout << tri->getType() << std::endl;
    return 0;
}

创建一个变量字符串类型。在每个可实例化的子类中设置它。在 Shape 中有一个函数 getType 来返回它。

上面的答案基本上是正确的:"我需要使用指针"是关键。

这解决了我的问题:

int main ()
{
    Polygon poly = Polygon();
    Shape* testing = &poly;
    std::cout << testing->getType() << std::endl;
    return 0;
}

我将在大约一个小时内接受您的答案,因为堆栈溢出让我在接受之前等待一段时间。谢谢

最新更新