虚继承时,共同基类中的变量只会保存一份,但是会有一个虚基类指针(具体内容不讨论 参考
为了避免对齐带来的干扰,把 int 换成 long long

继承关系如下

全部是空类的情况

  1. class Base {
  2. public:
  3. //long long a = 0;
  4. };
  5. class Derived1 : virtual public Base {
  6. public:
  7. //long long b1 = 100;
  8. };
  9. class Derived2 : virtual public Base {
  10. public:
  11. //long long b2 = 200;
  12. };
  13. class Derived : public Derived1, public Derived2 {
  14. public:
  15. //long long d = 200;
  16. };
  17. int main() {
  18. cout << sizeof(Base) << endl;
  19. cout << sizeof(Derived1) << endl;
  20. cout << sizeof(Derived2) << endl;
  21. cout << sizeof(Derived) << endl;
  22. return 0;
  23. }

结果
image.png
其中 Base 类是空类,但是为了让每一个类的实例都占用一个独特的内存空间,所以会由编译器隐含的分配一个char。
Derived1Derived2 各有一个虚基类指针,古大小为8字节, Derived 的大小为16字节,即为两个继承来的虚基类指针。

Base非空的情况

  1. class Base {
  2. public:
  3. long long a = 0;
  4. };
  5. class Derived1 : virtual public Base {
  6. public:
  7. //long long b1 = 100;
  8. };
  9. class Derived2 : virtual public Base {
  10. public:
  11. //long long b2 = 200;
  12. };
  13. class Derived : public Derived1, public Derived2 {
  14. public:
  15. //long long d = 200;
  16. };
  17. int main() {
  18. cout << "sizeof(Base) = " << sizeof(Base) << endl;
  19. cout << "sizeof(Derived1) = " << sizeof(Derived1) << endl;
  20. cout << "sizeof(Derived2) = " << sizeof(Derived2) << endl;
  21. cout << "sizeof(Derived) = " << sizeof(Derived) << endl;
  22. return 0;
  23. }

结果
image.png
可见 Base 中的变量 aDerived 中只保留了一份

全部非空

  1. class Base {
  2. public:
  3. long long a = 0;
  4. };
  5. class Derived1 : virtual public Base {
  6. public:
  7. long long b1 = 100;
  8. };
  9. class Derived2 : virtual public Base {
  10. public:
  11. long long b2 = 200;
  12. };
  13. class Derived : public Derived1, public Derived2 {
  14. public:
  15. long long d = 200;
  16. };
  17. int main() {
  18. cout << "sizeof(Base) = " << sizeof(Base) << endl;
  19. cout << "sizeof(Derived1) = " << sizeof(Derived1) << endl;
  20. cout << "sizeof(Derived2) = " << sizeof(Derived2) << endl;
  21. cout << "sizeof(Derived) = " << sizeof(Derived) << endl;
  22. return 0;
  23. }

结果
image.png

计算公式为

  1. sizeof(Derived) = (sizeof(Derived1) - sizeof(Base))
  2. + (sizeof(Derived2) - sizeof(Base))
  3. + sizeof(Base)
  4. + (Derived类内定义的变量的size)