12.3.1 类对象占用的内存空间
1、空类占用1字节
C++编译器会给每个空对象分配一个字节的空间,用于区分每个空对象在内存中的位置。
每个空对象也应该有自己的独有的位置。
#include<iostream>
#include<string>
using namespace std;
class person
{
};
int main()
{
person p;
cout << "size of p = " << sizeof(p) << endl;
system("pause");
return 0;
}
2、非静态成员变量属于类的成员,会增加类占用的空间
#include<iostream>
#include<string>
using namespace std;
class person
{
int m_A;
};
int main()
{
person p;
cout << "size of p = " << sizeof(p) << endl;
system("pause");
return 0;
}
在person类中加入一个非静态成员变量,发现类对象占用4字节,如果再加一个int型,就是8字节。
3、静态成员变量不属于类的对象上,不增加内存空间。
#include<iostream>
#include<string>
using namespace std;
class person
{
int m_A;
static int m_B;
};
int person::m_B = 10;
int main()
{
person p;
cout << "size of p = " << sizeof(p) << endl;
system("pause");
return 0;
}
看到,占用的空间仍然是4字节。
4、成员变量和成员函数分开存储,成员函数无论是静态还是非静态都不增加类的占用空间。
#include<iostream>
#include<string>
using namespace std;
class person
{
int m_A;
static int m_B;
void func1(){}
static void func2(){}
};
int person::m_B = 10;
int main()
{
person p;
cout << "size of p = " << sizeof(p) << endl;
system("pause");
return 0;
}
可以看到,占用的空间仍然是4.
综上所述,只有非静态成员变量属于类的对象上,会增加类占用的内存,其他都不会增加。