32位机器,sizeof(cTest)=?
class CTest
{
public:
CTest():m_chData(‘\0’),m_nData(0)
{
}
virtual void mem_fun(){}
private:
char m_chData;
int m_nData;
static char s_chData;
};
我的分析如下:
由于有虚函数,所以虚函数指针占4个字节,然后char占一个字节,按4字节对齐,补三位,int 占4个字节 最后static占4个字节。可是运行结果却不是16。
这是什么原因呢?
我在电脑上试图打出CTest类里每个对象的地址,s_chData的地址如何查看呢?
我的代码如下:
int main()
{
CTest example;
cout<<&example<<endl;
cout<<&(example.m_chData)<<endl;
cout<<&(example.m_nData)<<endl;
return 0;
}
输出结果
0x7fff5fbff7a8
0x7fff5fbff7b4
中间有一个空行,然后试图输出s_chData的地址时提示错误。
In a class, if there is nothing, the class occupies 1 byte. Once there are other space-occupying members in the class, this 1 byte is not included in the calculation. If a class has only one int, it occupies 4 bytes instead of 5 bytes.
If there are only member functions, it still only occupies 1 byte, because class functions do not occupy space. Virtual functions require 4 bytes because there is a virtual function table. If the data member object is a pointer, it takes 4 bytes. Note that there is byte alignment. If it is 13 bytes, it will be carried to 16 bytes of space.
static needs to be initialized outside the class, the static variable is in the static storage area, and the class object is allocated in the stack space