下面的编码碎片。
/*This program demonstartes how a virtual table pointer
* adds to a size of a class*/
class A{
};
class X{
public:
void doNothing(){}
private:
char a;
};
class Z:public X {
public:
void doNothing(){}
private:
char z;
};
class Y{
public:
virtual void doNothing(){}
private:
char a;
};
class P:public Y {
public:
void doNothing(){}
private:
char pp[4];
};
int main(){
A a;
X x;
Y y;
Z z;
P p;
std::cout << "Size of A:" << sizeof(a) << std::endl;// Prints out 1
std::cout << "Size of X:" << sizeof(x) << std::endl;//Prints out 1
std::cout << "Size of Y:" << sizeof(y) << std::endl;//Prints 8
std::cout << "Size of Z:" << sizeof(z) << std::endl;
//Prints 8 or 12 depending upon wether 4 bytes worth of storrage is used by Z data member.
std::cout << "Size of P:" << sizeof(p) << std::endl;
std::cout << "Size of int:" << sizeof(int) << std::endl;
std::cout << "Size of int*:" << sizeof(int*) << std::endl;
std::cout << "Size of long*:" << sizeof(long*) << std::endl;
std::cout << "Size of long:" << sizeof(long) << std::endl;
return 0;
}
我似乎注意到的行为是,如果一个空档阶级被当成时,或者一个空洞的阶级从秘密继承(即允许一个大小1的物体),那么在所有其他情况下,物体的规模似乎都由逐个边界决定。
原因何在? 我自此问,我是猜测。