在下面,如何使程序使用draw中的MainMenuScreen方法而不是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完全设为虚拟,所以请提出其他建议。

最佳答案

我怎样才能使程序使用来自
  MainMenuScreen而不是GameScreen中的一个?


您不能,除非您在实际类型为MainMenuScreen的指针或引用上调用它。

 list<GameScreen> screens;


声明对象的list,而不是指针或引用。如果向其中添加MainMenuScreen对象,由于对象切片,它们将丢失类型信息,并且多态性将不起作用。你需要:

 list<GameScreen*> screens;


或者,更好的是:

 list<shared_ptr<GameScreen> > screens;

10-04 12:59