[英]Use of virtual functions in derived classes
In the following class, i'm aware the output will be: 在下面的类中,我知道输出将是:
Func A game Func游戏
Func B game 功能B游戏
Func A game Func游戏
Func B game 功能B游戏
and to fix it would be to make the Game functionB() virtual but I was just wondering why rpg->functionB() would call the method in the Game class as opposed to the RPG class? 并解决它是使Game functionB()虚拟,但是我只是想知道为什么rpg-> functionB()会在Game类而不是RPG类中调用该方法? Can anyone help?
有人可以帮忙吗?
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;
}
I don't see any functions declared virtual
in your code. 我在您的代码中看不到任何声明为
virtual
函数。 Only virtual functions are resolved at runtime; 在运行时仅解析虚拟函数。 non-virtual functions are resolved at compile time, according to the static type.
根据静态类型,可以在编译时解析非虚拟函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.