对于以下代码片段。
/*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 字节的对象),在所有其他情况下,对象大小似乎由字节边界。
这是什么原因?我问,因为在这一点上我猜。