c++ - 继承/多态——子类的调用方法

标签 c++ inheritance

在下面,我怎样才能使程序使用 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/

相关文章:

c++ - 对 vector 的相同元素进行升序排序

c++ - 是否有任何关于为什么重新定义枚举器格式错误的规则?

c++ - 当没有容器时作为迭代器返回什么?

具有更多方法的 Python 子类

java - Hibernate继承: Schema-validation: missing column

c++ - 继承istream运算符>>

c++ - 为什么我继承的构造函数调用我的基本默认构造函数

c++ - 为什么这个循环不检测空指针?

php - 从文件解析数据后使用舍入函数

java - 如何在没有多重继承的情况下做到这一点