一、虚拟菱形继承
#include <iostream>
using namespace std;class B {
public:int _b;
};class C1 :virtual public B {
public:int _c1;
};class C2 :virtual public B {
public:int _c2;
};class D :public C1, public C2 {
public:int _d;
};int main()
{cout << sizeof(D); //24return 0;
}
二. 虚拟菱形继承
测试代码:
#include <iostream>
using namespace std;
struct A
{A(int v = 100) : X(v) {};virtual void foo(void) {}int X;
};struct B : virtual public A
{B(int v = 10) :Y(v), A(100) {};virtual void fooB(void) {}int Y;
};struct C : virtual public A
{C(int v = 20) :Z(v), A(100) {}virtual void fooC(void) {}int Z;
};struct D : public B, public C
{D(int v = 40) :B(10), C(20), A(100), L(v) {}virtual void fooD(void) {}int L;
};int main()
{A a;int* ptr;ptr = (int*)&a;cout << ptr << " sizeof = " << sizeof(a) << endl;for (int i = 0; i < sizeof(A) / sizeof(int); i++){if (ptr[i] < 10000){cout << dec << ptr[i] << endl;}elsecout << hex << ptr[i] << " = " << hex << *((int*)(ptr[i])) << endl;}cout << "--------------------------------------" << endl;B b;ptr = (int*)& b;cout << "addr:" << ptr << " sizeof = " << sizeof(b) << endl;for (int i = 0; i < sizeof(B) / sizeof(int); i++){if (ptr[i] < 10000){cout << dec << ptr[i] << endl;}elsecout << hex << ptr[i] << " = " << hex << *((int*)(ptr[i])) << endl;}cout << "--------------------------------------" << endl;D d;ptr = (int*)& d;cout << "addr:" << ptr << " sizeof = " << sizeof(d) << endl;for (int i = 0; i < sizeof(D) / sizeof(int); i++){if (ptr[i] < 10000){cout << dec << ptr[i] << endl;}elsecout << hex << ptr[i] << " = " << hex << *((int*)(ptr[i])) << endl;}return 0;
}
输出结果:
参考资料
- 图说C++对象模型:对象内存布局详解
- 从内存布局看C++虚继承的实现原理
- C++继承内存对象模型