#include<iostream>
#include<string>
using namespace std;
class Person {
public:
};
void test01() {
Person p;
cout << "空对象所占内存空间" << sizeof(p) << endl;
}
int main() {
test01();
return 0;
}
//C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置,每个空对象也要有一个独一无二的内存空间。
在类中加入一个非静态成员
#include<iostream>
#include<string>
using namespace std;
class Person {
public:
int m_A;//非静态成员变量
};
void test01() {
Person p;
cout << "空对象所占内存空间" << sizeof(p) << endl;
}
int main() {
test01();
return 0;
}
在类中再加入一个静态成员
#include<iostream>
#include<string>
using namespace std;
class Person {
public:
int m_A;//非静态成员变量
static int m_B;
};
void test01() {
Person p;
cout << "空对象所占内存空间" << sizeof(p) << endl;
}
int main() {
test01();
return 0;
}
发现运行结果还是和上次一样,原因是静态成员变量不属于类对象,非静态成员变量属于类对象
再加入非静态成员函数结果还是和上次一样,表明函数也不属于类对象,进而表明,成员函数和成员变量是分开放的