分享一道类继承的笔试题目

转自:http://blog.csdn.net/liuzhanchen1987/article/details/8074714


[cpp]  view plain copy
  1. <pre class="cpp" name="code">#include<iostream>  
  2. using namespace std;  
  3. class A  
  4. {  
  5. public:  
  6.     virtual void fun1()  
  7.     {  
  8.         cout<<"A fun1"<<endl;  
  9.     }  
  10.     void fun2()  
  11.     {  
  12.         cout<<"A fun2"<<endl;  
  13.     }  
  14. };  
  15. class B :public A  
  16. {  
  17. public:  
  18.     void fun1()  
  19.     {  
  20.         cout<<"B fun1"<<endl;  
  21.     }  
  22.     void fun2()  
  23.     {  
  24.         cout<<"B fun2"<<endl;  
  25.     }  
  26. };  
  27. int main()  
  28. {  
  29.     B *obB=new B;  
  30.     A *obA=(A*)obB;  
  31.     obA->fun1();  
  32.     obA->fun2();  
  33.     cout<<endl;  
  34.     obA = (B*)obA;  
  35.     obA->fun1();  
  36.     obA->fun2();cout<<endl;  
  37.     A *a1=new A;  
  38.     B *b1=(B*)a1;  
  39.     a1->fun1();  
  40.     a1->fun2();cout<<endl;  
  41.     a1=(A*)a1;  
  42.     a1->fun1();  
  43.     a1->fun2();  
  44.     cout<<endl;  
  45.     B b2;  
  46.     A a2=b2;//对象类型进行了转换  
  47.     a2.fun1();  
  48.     a2.fun2();cout<<endl;  
  49.     A a3;  
  50. //  B b3=(B)a3; 不可以转换  
  51.     return 0;  
  52.   
  53. }</pre><br>  
  54. <pre><pre class="cpp" name="code">对于多态,调用子类的函数还是父类的函数是由其对象决定的,不是由指针决定的,  
  55. 输出结果是:</pre><pre class="cpp" name="code">B fun1  
  56. A fun2</pre><pre class="cpp" name="code">父类指针指向子类,如果父类函数为虚函数则调用子函数,否则调用父类中函数。 B fun1  
  57. A fun2</pre><pre class="cpp" name="code">将原先指向子类的父类再转换成子类,不太清楚为什么是以上输出,欢迎大牛指点派生类指针指向基类,调用的函数全是基类的,因为该对象没有被转换成派生类对象A fun1  
  58. A fun2</pre><pre class="cpp" name="code">A fun1  
  59. A fun2</pre><pre class="cpp" name="code">派生类完全转换成基类对象</pre><pre class="cpp" name="code">A fun1</pre><pre class="cpp" name="code">A fun2</pre><br></pre>  
  60. <pre></pre>  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值