- #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;}
- virtual void h(){cout << "A::h() called." << endl;}
- private:
- int x;
- };
- class B:public A
- {
- public:
- B(int a,int b):A(a),y(b){}
- void f(){cout << "B::f() called." << endl;}
- virtual void m(){cout << "B::m() called." << endl;}
- virtual void n(){cout << "B::n() called." << endl;}
- private:
- int y;
- };
- class C:public A
- {
- public:
- C(int a,int c):A(a),z(c){}
- void g(){cout << "C::g() called." << endl;}
- virtual void cfun(){cout << "C::cfun() called." << endl;}
- private:
- int z;
- };
- class D:public B,public C
- {
- public:
- D(int a,int b,int c,int d):B(a,b),C(a,c),d(d){}
- void h(){cout << "D::h() called." << endl;}
- void m(){cout << "D::m() called." << endl;}
- virtual void t(){cout << "D::t() called." << endl;}
- private:
- int d;
- };
- int main()
- {
- D tp(2,3,4,5);
- typedef void (*PFUN)(void);
- PFUN pfun;
- pfun = (PFUN)(*((int*)(*(int*)(&tp))));
- pfun();
- pfun = (PFUN)(*((int*)(*(int*)(&tp))+1));
- pfun();
- pfun = (PFUN)(*((int*)(*(int*)(&tp))+2));
- pfun();
- pfun = (PFUN)(*((int*)(*(int*)(&tp))+3));
- pfun();
- pfun = (PFUN)(*((int*)(*(int*)(&tp))+4));
- pfun();
- pfun = (PFUN)(*((int*)(*(int*)(&tp))+5));
- pfun();
- cout << *((int*)(&tp) + 1) << endl;
- cout << *((int*)(&tp) + 2) << endl;
- pfun = (PFUN)(*(int*)(*((int*)(&tp) + 3)));
- pfun();
- pfun = (PFUN)(*((int*)(*((int*)(&tp) + 3))+1));
- pfun();
- pfun = (PFUN)(*((int*)(*((int*)(&tp) + 3))+2));
- pfun();
- pfun = (PFUN)(*((int*)(*((int*)(&tp) + 3))+3));
- pfun();
- cout << *((int*)(&tp) + 4) << endl;
- cout << *((int*)(&tp) + 5) << endl;
- cout << *((int*)(&tp) + 6) << endl;
- return 0;
- }
对像模型:
------------------------------------------------------------------------------------
从输出结果上我们可以看到A::x在对象D中有两份。一份来自于B,一份来自于C。这不仅浪费的存储空间,而且容易造成歧义。故此引入了虚拟继承。