#include "stdafx.h"
#include <iostream>
using namespace std;
class ClassA
{
protected:
int width, height;
public:
void set_values(int x, int y)
{
width = x;
height = y;
}
};
class ClassB : virtual public ClassA
{
//12(int + int + vptr)
};
class ClassC : virtual public ClassA
{
//12(int + int + vptr)
};
class ClassD : public ClassB, public ClassC
{
};
int main()
{
ClassA A;
ClassB B;
ClassC C;
ClassD D;
cout << "size = " << sizeof(A) << endl;
cout << "size = " << sizeof(B) << endl;
cout << "size = " << sizeof(C) << endl;
cout << "size = " << sizeof(D) << endl;
return 0;
}
我得到的输出是:
size of ClassA = 8
size of ClassB = 12
size of ClassC = 12
size of ClassD = 16
在上面的代码中,为什么 ClassD 的输出是 16。请清楚地解释一下这个虚拟继承是如何工作的。