【问题标题】:C++ inheritance not workingC ++继承不起作用
【发布时间】:2013-04-24 16:59:29
【问题描述】:

我正在制作一个游戏,在游戏中有一个包含玩家的列表,该列表处理 Player 类。我还有一个类,它是 Player 的一个孩子,叫做 HumanPlayer。我在玩家列表中添加了一个人类玩家。但是当我运行渲染函数时,它不会从humanplayer 渲染,而是从播放器渲染。 render 函数是一个虚函数,应该被覆盖,但不是。

这是我定义列表的地方:

std::list<Player> playerList;

这是我在列表中添加人类玩家的地方:

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

这里是渲染函数调用渲染的地方:

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

【问题讨论】:

标签: c++ list function inheritance


【解决方案1】:

你正在做它所谓的Slicing。为了使多态性起作用,您需要使用pointers 或references。最基本的解决方案是改用pointer

std::list<Player*> playerList;

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

【讨论】:

  • 使用指针改变了他的代码中的许多东西;特别是,每个玩家只有一个实例,而不是很多。 std::unique_ptr 在这里不太合适; std::shared_ptr 可能,但最合适的指针很有可能是原始指针。
  • @JamesKanze 谢谢,修改答案
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 2015-03-04
      • 2012-06-04
      相关资源
      最近更新 更多