C++对象模型-----多继承

Code:
  1. #include <iostream>   
  2. using namespace std;   
  3. class A   
  4. {   
  5. public:   
  6.     A(int a):x(a){}   
  7.     virtual void f(){cout << "A::f() called." << endl;}   
  8.     virtual void g(){cout << "A::g() called." << endl;}   
  9.     void h(){cout << "A::h() called." << endl;}   
  10. private:   
  11.     int x;   
  12. };   
  13. class B   
  14. {   
  15. public:   
  16.     B(int b):y(b){}   
  17.     virtual void k(){cout << "B::k() called." << endl;}   
  18.     virtual void t(){cout << "B::t() called." << endl;}   
  19.     void m(){cout << "B::m() called." << endl;}   
  20. private:   
  21.     int y;   
  22. };   
  23. class C:public A,public B   
  24. {   
  25. public:   
  26.     C(int a,int b,int c):A(a),B(b),z(c){}   
  27.     void f(){cout << "C::f() called." << endl;}   
  28.     void k(){cout << "C::k() called." << endl;}   
  29.     virtual void n(){cout << "C::n() called." << endl;}   
  30. private:   
  31.     int z;   
  32. };   
  33. int main()   
  34. {   
  35.     C t(1,6,8);   
  36.     typedef void (*PFUN)();       
  37.     PFUN pfun;       
  38.     pfun = (PFUN)(*(int*)(*(int*)(&t)));       
  39.     pfun();       
  40.     pfun = (PFUN)(*((int*)(*(int*)(&t))+1));       
  41.     pfun();       
  42.     pfun = (PFUN)(*((int*)(*(int*)(&t))+2));       
  43.     pfun();   
  44.     cout << *((int*)(&t)+1) << endl;   
  45.     pfun = (PFUN)(*(int*)(*((int*)(&t)+2)));   
  46.     pfun();   
  47.     pfun = (PFUN)(*((int*)(*((int*)(&t)+2))+1));   
  48.     pfun();    
  49.     cout << *((int*)(&t)+3) << endl;   
  50.     cout << *((int*)(&t)+4) << endl;   
  51.     return 0;   
  52. }  

运行结果:

 

类C的对像模型:

---------------------------------------------------------------------------------

第一部分: 第一个基类部分

4B    A::vptr --------------------------------------->C::f();

 4B   A::x;                                                           A::g();

                                                                           C::h();

-------------------------------------------------------------------------------------

第二部分:第二个基类部分

 4B   B::vptr --->   C::k();   

  4B   B::y;              B::t();

-------------------------------------------------------------------------------------

第三部分:自己的部分

  4B   C::z;

--------------------------------------------------------------------------------------

注意:自己部分的虚函数被放到了第一个基类部分的虚函数表中。对于重写的虚函数覆盖原来虚函数的slot。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值