形状.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/