#include<iostream>
#include<list>
using namespace std;
class Point3d
{
public:
float x;
static list<Point3d*> *freeelist;
float y;
static const int size = 250;
char n;
float z;
};
int main()
{
Point3d model;
cout << "char:" << sizeof(char) << endl;
cout << "int:" << sizeof(int) << endl;
cout << "float:" << sizeof(float) << endl;
cout << "对象大小为:" << sizeof(model) << endl;
cout << "the address of model: "<<&model << endl;
cout << "the address of the x member: " << &(model.x) << endl;
cout << "the address of the y member: " << &(model.y) << endl;
cout << "the address of the z member: " << &(model.z) << endl;
}
这段代码的执行结果如下图所示:
单独对char类型进行sizeof运算时,是大小为1byte,但是放在对象中是,对类对象记性sizeof运算时,char的大小被调整为4bytes,这是基于编译器和计算机的Alignment的限制。在大部分机器中,为了更有效率的存取,此处将char补齐为4bytes。此外,对于c++对象,类中会出现多个access sections,为了验证在我机器上,gcc 4.7.3 编译器下,不同访问级别下数据成员的排列情况,代码如下图所示:
#include<iostream>
#include<list>
using namespace std;
class Point3d
{
public:
float x;
static list<Point3d*> *freeelist;
float y;
static const int size = 250;
private:
char n;
public:
float z;
};
int main()
{
Point3d model;
cout << "char:" << sizeof(char) << endl;
cout << "int:" << sizeof(int) << endl;
cout << "float:" << sizeof(float) << endl;
cout << "对象大小为:" << sizeof(model) << endl;
cout << "the address of model: "<<&model << endl;
cout << "the address of the x member: " << &(model.x) << endl;
cout << "the address of the y member: " << &(model.y) << endl;
cout << "the address of the z member: " << &(model.z) << endl;
}
对于char数据仍然占有4bytes,保存在两个public access label中间,和其声明顺序相同。
此处有个疑问没有理解:在这种情况下,即public数据和private数据存储顺序和声明顺序相同,但是靠什么来识别它们不同数据成员的访问级别呢?根据对象的大小可以看出并没有添加其他成员来标示它们的访问级别?