- #include <iostream>
- using namespace std;
- class A
- {
- public:
- A(int a):x(a){}
- virtual void f(){cout << "A::f() called." << endl;}
- virtual void g(){cout << "A::g() called." << endl;}
- void h(){cout << "A::h() called." << endl;}
- private:
- int x;
- };
- class B
- {
- public:
- B(int b):y(b){}
- virtual void k(){cout << "B::k() called." << endl;}
- virtual void t(){cout << "B::t() called." << endl;}
- void m(){cout << "B::m() called." << endl;}
- private:
- int y;
- };
- class C:public A,public B
- {
- public:
- C(int a,int b,int c):A(a),B(b),z(c){}
- void f(){cout << "C::f() called." << endl;}
- void k(){cout << "C::k() called." << endl;}
- virtual void n(){cout << "C::n() called." << endl;}
- private:
- int z;
- };
- int main()
- {
- C t(1,6,8);
- typedef void (*PFUN)();
- PFUN pfun;
- pfun = (PFUN)(*(int*)(*(int*)(&t)));
- pfun();
- pfun = (PFUN)(*((int*)(*(int*)(&t))+1));
- pfun();
- pfun = (PFUN)(*((int*)(*(int*)(&t))+2));
- pfun();
- cout << *((int*)(&t)+1) << endl;
- pfun = (PFUN)(*(int*)(*((int*)(&t)+2)));
- pfun();
- pfun = (PFUN)(*((int*)(*((int*)(&t)+2))+1));
- pfun();
- cout << *((int*)(&t)+3) << endl;
- cout << *((int*)(&t)+4) << endl;
- return 0;
- }
运行结果:
类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。