测试代码
#include <stdio.h>
struct AA
{
char b;
char b1;
int b3;
char b2;
};
class A
{
public:
A() { b = 'a'; }
A(char c){
b = c;
printf("build A:%c
",c);
}
char b;
char a;
char c;
};
class B :virtual public A
{
public:
B():A('B'){
printf("build B
");
b = 'b';
a = 'b';
}
char b;
};
class C :virtual public A
{
public:
C() :A('C') {
printf("build C
");
b = 'c';
a = 'c';
}
char b;
};
class D :public C, public B,public A
{
public:
};
int main(int argc, char* argv[])
{
D d;
printf("%d
", sizeof(struct AA));
printf("%d
", sizeof(A));
printf("%d
", sizeof(B));
printf("%d
", sizeof(C));
printf("%d
", sizeof(D));
printf("%c %c %c
",d.A::b, d.B::b, d.C::b);
printf("%c %c
", d.B::a, d.C::a);
return 0;
}
build C #按继承顺序调用构造函数
build B
12 #结构体按最大字节对齐(可能的值有8,4,2,1) double 8 float int 指针 4 short 2 char 1
3 # 3个char --- 用1对齐 1+1+1=3
11 # 虚继承A的3个char(虚继承的类没有内存对齐) 1个虚地址指针 1个char --- 用4对齐 3+4+4=11
11 # 同上
23 # 虚继承A的3个char B类的1个指针和1个char C类的1个指针和1个char A类3个char --- 用4对齐 3+(4+4)+(4+4)+4=23
a b c # 'a' 是从A中继承的b,可以通过d.B::A::b访问通过B继承的A中的B
b b # 虚继承共享A类内存,所以值相同,因为B后继承,构造函数后调用,所以输出'b'
自己尝试,留个记录