对象的大小
对于对象的大小我遇到了几个困惑,想请教一下各位
一、我定义了一个如下形式的类A
class A
{
};
不含任何成员,在VC6.0下用sizeof(A)测试时输出为1,对于不含任何数据成员的类,系统为它分配的这一个字节空间存放什么呢?
二、再有如下基类(Student)和派生类(Student1)
class Student
{
public:
Student()
{
cout<<"please input"<<endl;
cout<<"num: ";
cin>>num;
cout<<"name: ";
cin>>name;
cout<<"sex: ";
cin>>sex;
}
void get_value()
{ cin>>num>>name>>sex;}
void display( )
{
cout<<endl;
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl;
}
private :
int num;
string name;
char sex;
};
class Student1: public Student
{
public:
Student1()
{
cout<<"age: ";
cin>>age;
cout<<"addr: ";
cin>>addr;
}
void display()
{
Student::display( );
cout<<"age: "<<age<<endl;
cout<<"address: "<<addr<<endl;
}
private:
int age;
string addr;
};
在VC6.0下的测试结果分别为
sizeof(Student)= 24, 而4+16(VC6.0下string占16字节)+1=21
sizeof(Student1)=44,而4+16+1+4+16=41
那么这分别多出的三个字节是什么呢?
三、对于下面的Box类,测试结果是12(正好是三个数据成员的和),为什么会有这样的差异呢?
class Box
{public:
Box();
Box(int h,int w ,int len):height(h),width(w),length(len){}
int volume();
private:
int height;
int width;
int length;
};
Box::Box()
{height=10;
width=10;
length=10;
}
int Box::volume()
{return(height*width*length);
}