c++ - 派生类中虚函数的使用

标签 c++ inheritance virtual

在接下来的类(class)中,我知道输出将是:

Func 游戏

Func B 游戏

玩游戏

Func B 游戏

要修复它,可以使 Game functionB() 成为虚拟的,但我只是想知道为什么 rpg->functionB() 会调用 Game 类而不是 RPG 类中的方法?谁能帮忙?

class Game  {

     public: Game() {}; 

    void functionA() {cout << "Func A game" << endl;}; 
    void functionB() {cout << "Func B game" << endl;}; 

};

class RolePlayGame: public Game { 

    public: RolePlayGame() {}; 
    void functionB(){ cout << "Func B role play" << endl; }; 

};

int main(){

    Game* g = new Game; Game* rpg = new RolePlayGame;

    g->functionA();
    g->functionB();
    rpg->functionA();
    rpg->functionB();
    delete g;
    delete rpg;

    return 0;
}

最佳答案

我没有在您的代码中看到任何声明为 virtual 的函数。只有虚函数在运行时被解析;非虚函数根据静态类型在编译时解析。

关于c++ - 派生类中虚函数的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782704/

相关文章:

c++ - 虚函数采用基类类型的参数

c++ - SDL: Blitting BMP to window surface 黑屏之谜

c++ - 为什么 C++ 构造函数在继承中需要默认参数?

c++ - 访问我只想存在于派生类中的函数

javascript - 在 Knockout 中扩展动态和映射数据

C++ 虚拟 + 保护?

c++ - 为什么叫动态绑定(bind)呢?

c++ - 使用 const void * 将 std::function 作为参数传递

c++ - 返回类时警告 : control may reach end of non-void function?

C++ Armadillo 和 OpenMp : Parallelization of summation of outer products - define reduction for Armadillo matrix