虚函数调用,parrent的函数使用

Ari*_*jar 1 c++ virtual function 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();
}
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

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.
}
Run Code Online (Sandbox Code Playgroud)

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

要获得完整的代码,这里是gitHub存储库:https://github.com/Aridjar/AW_like

das*_*ght 8

你看到的是所谓的对象切片.当您将MenuBase对象放在对象的向量容器中时Menu,Base类中不存在的任何功能都会"切掉"对象; 只保留基类的功能.对象的行为不会超出您放入容器的类的范围之外的多态性.

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

std::vector< std::shared_ptr<Menu> > _graph;
Run Code Online (Sandbox Code Playgroud)