在下面,我怎样才能使程序使用 MainMenuScreen
中的 draw
方法而不是 GameScreen
中的方法?
class GameScreen {
public:
virtual void GameScreen::draw() {
cout << "Drawing the wrong one..." << endl;
}
};
class MainMenuScreen : public GameScreen {
public:
void MainMenuScreen::draw() {
cout << "Drawing the right one..." << endl;
}
};
class ScreenManager {
public:
list<GameScreen> screens;
// assume a MainMenuScreen gets added to the list
void ScreenManager::draw()
{
for ( list<GameScreen>::iterator screen = screens.begin();
screen != screens.end(); screen++ )
{
screen->draw(); /* here it uses the draw method from GameScreen,
but I want it to use the draw method from
MainMenuScreen */
}
}
};
PS:我不想让 GameScreen::draw
纯虚拟,所以请提出其他建议。
最佳答案
how can I make it such that the program uses the draw method from MainMenuScreen instead of the one from GameScreen?
你不能,除非你在实际类型为 MainMenuScreen
的指针或引用上调用它。
list<GameScreen> screens;
声明对象的列表
,而不是指针或引用。如果向其中添加 MainMenuScreen
对象,由于对象切片,它们将丢失类型信息,并且多态性将不起作用。你需要:
list<GameScreen*> screens;
或者,更好的是:
list<shared_ptr<GameScreen> > screens;
关于c++ - 继承/多态——子类的调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9934427/