虚继承时,共同基类中的变量只会保存一份,但是会有一个虚基类指针(具体内容不讨论 参考 )
为了避免对齐带来的干扰,把 int 换成 long long
全部是空类的情况
class Base {public://long long a = 0;};class Derived1 : virtual public Base {public://long long b1 = 100;};class Derived2 : virtual public Base {public://long long b2 = 200;};class Derived : public Derived1, public Derived2 {public://long long d = 200;};int main() {cout << sizeof(Base) << endl;cout << sizeof(Derived1) << endl;cout << sizeof(Derived2) << endl;cout << sizeof(Derived) << endl;return 0;}
结果
其中 Base 类是空类,但是为了让每一个类的实例都占用一个独特的内存空间,所以会由编译器隐含的分配一个char。Derived1 与 Derived2 各有一个虚基类指针,古大小为8字节, Derived 的大小为16字节,即为两个继承来的虚基类指针。
Base非空的情况
class Base {public:long long a = 0;};class Derived1 : virtual public Base {public://long long b1 = 100;};class Derived2 : virtual public Base {public://long long b2 = 200;};class Derived : public Derived1, public Derived2 {public://long long d = 200;};int main() {cout << "sizeof(Base) = " << sizeof(Base) << endl;cout << "sizeof(Derived1) = " << sizeof(Derived1) << endl;cout << "sizeof(Derived2) = " << sizeof(Derived2) << endl;cout << "sizeof(Derived) = " << sizeof(Derived) << endl;return 0;}
结果
可见 Base 中的变量 a 在 Derived 中只保留了一份
全部非空
class Base {public:long long a = 0;};class Derived1 : virtual public Base {public:long long b1 = 100;};class Derived2 : virtual public Base {public:long long b2 = 200;};class Derived : public Derived1, public Derived2 {public:long long d = 200;};int main() {cout << "sizeof(Base) = " << sizeof(Base) << endl;cout << "sizeof(Derived1) = " << sizeof(Derived1) << endl;cout << "sizeof(Derived2) = " << sizeof(Derived2) << endl;cout << "sizeof(Derived) = " << sizeof(Derived) << endl;return 0;}
计算公式为
sizeof(Derived) = (sizeof(Derived1) - sizeof(Base))+ (sizeof(Derived2) - sizeof(Base))+ sizeof(Base)+ (Derived类内定义的变量的size)
