静态成员变量
- 编译阶段分配内存
- 所有对象共享数据
- 通过对象访问、通过类名访问
- 有权限控制
- 在类内声明,类外进行初始化
不可以在类内进行初始化,也不可以在构造函数内进行初始化
#include<iostream>
using namespace std;
class Nick {
public:
Nick() {
//m_id = 180618;
}
static int m_id; //加入static就是静态成员变量,会共享数据
private:
static int m_password;
};
int Nick::m_id = 180618; //类外初始化实现
int Nick::m_password = 1113;
void test01() {
//通过对象访问数据
Nick n1;
n1.m_id = 37;
Nick n2;
n2.m_id = 31;
cout << "n1=" << n1.m_id << endl;//20 共享数据
cout << "n2=" << n2.m_id << endl;//20
//通过类名访问属性
cout << "通过类名访问ID:" << Nick::m_id << endl;//20
//cout << "other=" << Nick::m_password << endl; //私有权限在类外无法访问
}
int main() {
test01();
system("pause");
return 0;
}