C++ 重写方法未被调用

标签 c++ inheritance virtual overriding

形状.h

namespace Graphics {
    class Shape {
    public:
        virtual void Render(Point point) {};
    };
}

矩形.h

namespace Graphics {
    class Rect : public Shape {
    public:
        Rect(float x, float y);
        Rect();
        void setSize(float x, float y);
        virtual void Render(Point point);

    private:
        float sizeX;
        float sizeY;
    };
}

struct ShapePointPair {
    Shape shape;
    Point location;
};

这样使用:

std::vector<Graphics::ShapePointPair> theShapes = theSurface.getList();

for(int i = 0; i < theShapes.size(); i++) {
    theShapes[i].shape.Render(theShapes[i].location);
}

此代码最终调用 Shape::Render 而不是 Rect::Render

我假设这是因为它将 Rect 转换为 Shape,但我不知道如何阻止它这样做。我试图通过覆盖 Render 方法让每个形状控制它的呈现方式。

关于如何实现这一点有什么想法吗?

最佳答案

这是你的问题:

struct ShapePointPair {
        Shape shape;
        Point location;
};

您正在存储 Shape .您应该存储 Shape * , 或 shared_ptr<Shape>或者其他的东西。但不是 Shape ; C++ 不是 Java。

当您分配 Rect 时到 Shape , 只有 Shape正在复制部分(这是对象切片)。

关于C++ 重写方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1444025/

相关文章:

C# 函数的继承和重写

multithreading - 虚拟Listview,线程和内存消耗不下降

linux - 4GB/4GB 内核 VM 拆分

c++ - 在 C++ 中添加互斥锁后结构中的赋值运算符

c++ - C++ 标准库是否比 winAPI 具有更多的环境依赖性?

c++ - 使用 node.js 访问以 c++ 编写的 SDK

c++ - 清理 QList 和 QGraphicsScene 以避免内存泄漏

php - 当 Controller 类扩展父 Controller 时,为什么我们仍然需要父构造函数?

python - 从 Python 中的基类导入子类

c++ - 我们可以在 C++ 中创建一个虚拟的类复制构造函数吗