【发布时间】:2010-11-29 11:08:55
【问题描述】:
形状.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 方法来控制它的呈现方式。
关于如何实现这一点的任何想法?
【问题讨论】:
-
也许您想向我们展示创建矢量元素的代码?
-
问题和解决方案与stackoverflow.com/questions/1230006这个问题几乎相同。在那里,您有一个(包含一个)具体基类的向量,如果您希望调用 Rect::Render,则必须通过 slicing 派生类创建该向量。
标签: c++ inheritance virtual overriding