代码改变世界

空类与多重继承占用空间大小

2022-11-15 21:31  钟铧若岩  阅读(14)  评论(0编辑  收藏  举报

虚继承涉及虚表(虚指针),所以sizeof(C) = 8

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A{};
 5 class A2{};
 6 class B:public A
 7 {};
 8 
 9 class C:public virtual B
10 {};
11 
12 class D:public A,public A2
13 {};
14 
15 int main(int argc,char *argv[])
16 {
17     cout << "sizeof(A)" << sizeof(A) <<endl;//1
18     cout << "sizeof(B)" << sizeof(B) <<endl;//1
19     cout << "sizeof(C)" << sizeof(C) <<endl;//8
20     cout << "sizeof(D)" << sizeof(D) <<endl;//1
21     return 0;
22     
23 }