使用虚函数,parrent函数

时间:2014-07-31 12:45:19

标签: c++ function virtual sfml

关于StackOverflow的第一个问题。我想为我糟糕的英语道歉。

我实际上正在为视频游戏开发菜单。我想清除代码,所以我想使用vector来调用不同的函数(比如为图片充电或修改文本)

这是代码:

Menu.hh:

class Menu
{
int _position
std::vector<Menu> _graph;
std::list<sf::Text> _text;
public:
//constructors and destructors
virtual std::list<sf::Text> &modifyText();
}

Menu.cpp

std::list<sf::Text> &modifyText()
{
std::cout << this->_position << std::endl;
this->_text = this->_graph[this->_position].modifyText();
return (this->_text); // don't care of the return
}

void Menu::initGame()
{
this->_graph.push_back(MenuBase()); 
// if i Put this code on the constructor, the constructor call himself and not the MenuBase constructor
this->modifyText();
}

MenuBase.hpp

class MenuBase : public Menu
{
//constructor and destructor
std::list<sf::Text &modifyText(){std::cout << "work" << std::endl; 
//I've more code, but it's just initialization of text and the return.
//The work is here to show what's happen on the standard output.
}

此代码的输出为:0,0然后是SegFault。我希望在标准输出上看到“0”然后“工作”。 那么,为什么不调用MenuBase函数?

要获得完整代码,请访问gitHub存储库:https://github.com/Aridjar/AW_like

1 个答案:

答案 0 :(得分:8)

您看到的内容称为Object Slicing。当您将MenuBase对象放在Menu个对象的向量容器中时,Base类中不存在的任何功能都会“切掉”您的对象;只保留基类的功能。对象的行为不再是超出您放入容器的类的边界的多态。

为了保持您想要的多态行为,请使用指针容器替换对象容器。为避免手动内存管理带来麻烦,请选择常规智能指针:

std::vector< std::shared_ptr<Menu> > _graph;