C ++覆盖方法不被调用 [英] C++ Overridden method not getting called

查看:110
本文介绍了C ++覆盖方法不被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Shape.h

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

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;
};

如此使用:

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

for(int i = 0; i < theShapes.size(); i++) {

	theShapes[i].shape.Render(theShapes[i].location);

}

此代码最后调用Shape :: Render :: Render

This code ends up calling Shape::Render and not Rect::Render

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

I'm assuming this is because it is casting the Rect to a Shape, but I don't have any idea how to stop it doing this. I'm trying to let each shape control how it is rendered by overriding the Render method.

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

Any ideas on how to achieve this?

推荐答案

这是您的问题:

struct ShapePointPair {
        Shape shape;
        Point location;
};

您正在存储 Shape 。你应该存储一个 Shape * 或者 shared_ptr< Shape> 或者什么。但不是 Shape ;

You are storing a Shape. You should be storing a Shape *, or a shared_ptr<Shape> or something. But not a Shape; C++ is not Java.

当您将 Rect 赋值给 Shape ,只有 Shape 部分被复制(这是对象切片)。

When you assign a Rect to the Shape, only the Shape part is being copied (this is object slicing).

这篇关于C ++覆盖方法不被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆