C ++继承不起作用

时间:2013-04-30 17:21:14

标签: c++ list function inheritance

我正在制作游戏,在游戏中有一个包含玩家的列表,此列表处理类玩家。我还有一个类是Player的一个名为HumanPlayer的子类。我在玩家列表中添加了一个人类玩家。但是当我运行渲染功能时,它不会从人类玩家渲染它从玩家渲染。渲染函数是一个虚函数,应该被覆盖但不是。

这是我定义列表的地方:

std::list<Player> playerList;

这里是我将人工玩家添加到列表中的位置:

playerList.push_front(HumanPlayer(512,512,&entityList));

这是render函数调用render的地方:

if(!playerList.empty()){
    std::list<Player>::iterator iter;
    for (iter = playerList.begin(); iter != playerList.end(); iter++){
       iter -> render(canvas);
    }
 }

3 个答案:

答案 0 :(得分:4)

你正在做它所谓的Slicing。为了使多态性起作用,您需要使用pointerreference s。最基本的解决方案是使用pointer代替:

std::list<Player*> playerList;

但现在您需要管理内存并记住delete您创建的所有实例。因此,Collin建议您could使用某种smart pointer std::shared_ptr。但最终你需要决定哪个对你的问题更有意义。

答案 1 :(得分:1)

首先 - 使用指针,其次 - 不要忘记让你的方法变得虚拟。

答案 2 :(得分:0)

您的对象是sliced,因为您存储的是值类型Player而不是指针。

请改为尝试:

std::list<std::unique_ptr<Player>> playerList;
playerList.push_front(std::unique_ptr<Player>(new HumanPlayer(512,512, &playerList)));