C++重写方法未被调用

Sim*_*les 10 c++ virtual inheritance overriding

Shape.h

namespace Graphics {
    class Shape {
    public:
        virtual void Render(Point point) {};
    };
}
Run Code Online (Sandbox Code Playgroud)

Rect.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;
};
Run Code Online (Sandbox Code Playgroud)

像这样使用:

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

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

这段代码最终会调用Shape::Render而不是Rect::Render

我假设这是因为它正在施放Rect到a Shape,但我不知道如何阻止它这样做.我试图通过重写Render方法让每个形状控制它的呈现方式.

关于如何实现这一点的任何想法?

dav*_*420 24

这是你的问题:

struct ShapePointPair {
        Shape shape;
        Point location;
};
Run Code Online (Sandbox Code Playgroud)

你正在存储一个Shape.你应该存储一个Shape *,或一个shared_ptr<Shape>或什么.但不是Shape; C++不是Java.

当您指定a RectShape,仅Shape复制零件(这是对象切片).