为了账号安全,请及时绑定邮箱和手机立即绑定

执行结果是1112;为什么执行show(b)的结果不是2呢 而执行display(b)的结果是2呢

#include<iostream>
using namespace std;
class GA{
 public:
 virtual int f(){return 1;
 }
};
class GB:public GA{
 public:
 virtual int f(){
     return 2; }
};
 void show(GA g){cout<<g.f();
 }
 void display(GA &g){cout<<g.f();
 }
 
 int main(void){
  GA a;
  GB b;
 show(a);
  display(a);
  show(b);
  display(b);
  system("pause");
  return 0;
 
 }

正在回答

2 回答

display(b)是GA引用方式 调用对象,虚函数调用的是派生类GB的对象。

show(b)调用的以GA基类的对象。

0 回复 有任何疑惑可以回复我~
show(GA g);    
//这里的g是GA的对象,所以输出就相当于是cout<<g.GA::f();
display(GA &g)
//这里的&g是引用了GB b;所以输出就相当于是在GB b这个对象下cout<<g.f();


1 回复 有任何疑惑可以回复我~
#1

慕哥8585337 提问者

蟹蟹?
2018-08-26 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
C++远征之继承篇
  • 参与学习       75222    人
  • 解答问题       249    个

继承,C++面向对象三大特征之一,通过编码实践方式讲解到操作层面

进入课程

执行结果是1112;为什么执行show(b)的结果不是2呢 而执行display(b)的结果是2呢

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信