一个空类的大小为1,“事实上并不是空的,它有一个隐晦的1byte,那是被编译器安插进去的一个char,这使得这个class的两个objects得以在内在中配置独一无二的地址”---《Inside the c++ object model》。解释:也要为空类的对象分配内存,如果空类大小为0,则对象不会有内存。
代码
class P : public X
{
};
//根本不会内存对齐
class V
{
public:
char name;
char name2;
char n3;
};
//静态变量不放在Cup中,所以为1
//“每一个static data member只有一个实体,存放在程序的data segment之中”
class Cup
{
public:
static const int p = 9;
};
class Point
{
public:
virtual int X()
{
cout << "Point.X/n"<< endl;
return 0;
}
};
class Vertex
{
public:
virtual int Y()
{
cout << "Vertex.X /n" << endl;
return 0;
}
};
//多重继承内存布局中,VerPt拥有Point的虚表指针和Vertex虚表指针,
//故为8个字节。
class VerPt : public Point, public Vertex
{
};
void main()
{
cout << sizeof(X) << endl;
cout << sizeof(P) << endl;
cout << sizeof(Y) << endl;
cout << sizeof(V) << endl;
cout << sizeof(A) << endl;
cout << sizeof(Cup) << endl;
cout << "VerPt" << sizeof(VerPt) << endl;
system("pause");
}
/*
1
1
4
3
8
1
VerPt8
*/