在C++中,类内的成员变量和成员函数分开存储
只有非静态成员变量才属于类的对象上

空对象

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;

class Person {
//空对象
};


int main() {
Person p;
cout << "sizeof(p)= " << sizeof(p);
return 0;
}
  • 输出结果为: sizeof(p)= 1

解释

  1. 空对象占用内存空间为: 1
  2. C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置
  3. 每个空对象也应该有一个独一无二的内存地址

非静态成员变量

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;

class Person {
int m_A;//非静态成员变量
};


int main() {
Person p;
cout << "sizeof(p)= " << sizeof(p);
return 0;
}
  • 输出结果: sizeof(p)= 4

结论

非静态成员变量属于类的对象上


静态成员变量

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;

class Person {
static int m_A;//静态成员变量
};

int Person::m_A = 0;

int main() {
Person p;
cout << "sizeof(p)= " << sizeof(p);
return 0;
}
  • 输出结果: sizeof(p)= 1

结论

静态成员变量不属于类的对象上


非静态成员函数

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;

class Person {
void func() {};//非静态成员函数
};


int main() {
Person p;
cout << "sizeof(p)= " << sizeof(p);
return 0;
}
  • 输出结果: sizeof(p)= 1

结论

非静态成员函数不属于类的对象上


静态成员函数

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;

class Person {
static void func() {};//非静态成员函数
};


int main() {
Person p;
cout << "sizeof(p)= " << sizeof(p);
return 0;
}
  • 输出结果: sizeof(p)= 1

结论

*** 静态成员函数不属于类的对象上