首先来说结论:
1.在C++中,类内的成员变量和成员函数分开存储
2.只有非静态成员变量才属于类的对象上
空类(类中上面对象都没没有)占用内存大小为:1
#include <iostream>
#include <string>
using namespace std;
class Person
{
};
void test01()
{
Person p;
cout << "空类的内存大小:" << sizeof(p) << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
可能会有人有这个疑问,为什么空类占用内存不是0呢,这是因为:
sizeof(A) > 0 是因为标准规定完整对象的大小为正数。因为每个内存都有它独有的代号 (首地址)
只有非静态成员变量才属于类的对象上的数据:
在类中添加一个成员变量:int m_A;
#include <iostream>
#include <string>
using namespace std;
class Person
{
private: //属性 一般私有
int m_A; //非静态成员变量
};
void test01()
{
Person p;
cout << "空类的内存大小:" << sizeof(p) << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
因为非静态成员变量 属于类的对象上
静态成员变量它不属于类的对象上面的数据:
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
int m_A;
static int m_B;
};
void test01()
{
Person p;
cout << "空类的内存大小:" << sizeof(p) << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
这里顺便说一下,静态成员变量需要在类内声明,类外初始化,当然我因为没使用那个变量就没声明
印证了那句静态成员变量不属于类对象的数据
类内的成员变量和(成员函数和静态成员函数)分开存储:
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
int Swap()
{
}
static double Fun()
{
}
private:
int m_A;
static int m_B;
};
void test01()
{
Person p;
cout << "空类的内存大小:" << sizeof(p) << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果不出所也是:4
总结一下:
类内的成员变量和成员函数分开存储!
无论是静态成员变量、静态成员函数、非静态成员函数 都不属于类对象上的数据。
只有非静态成员变量属于类对象上的数据!