关于C++类中的成员变量和成员函数是如何存储的,先看一下代码
#include <iostream>
using namespace std;
class Person1{};
class Person2 {
int m_a;
static int m_b;
void func() {}
static void func2() {}
};
void test01(void) {
Person1 p;
cout << "size of p=" << sizeof(p) << endl;
}
void test02(void) {
Person2 p;
cout << "size of p=" << sizeof(p) << endl;
}
int main(void)
{
test01();
test02();
system("pause");
return 0;
}
运行结果如下:
Person1定义的空对象p,占内存一个字节。这是因为C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置,因此每个空对象也有一个独一无二的内存地址。
Person2定义的对象p,占内存四个字节。这是因为当类对象非空时,则按其成员变量所占内存计算,只有非静态成员变量在类上,一个int占有4个字节
int m_a; /*非静态成员变量,属于类的对象上*/
static int m_b; /*静态成员变量,不属于类的对象上*/
void func() {} /*非静态成员函数,不属于类的对象上*/
static void func2() {}/*静态成员函数,不属于类的对象上*/