#include<iostream>
using namespace std;
#include<string>
class person{
public:
//静态成员变量
//1.所有对象都共享同一份数据
//2.编译阶段就分配内存
// 3.类内声明,类外初始化操作
static int m_a;//(类内声明)
//静态成员变量也是有访问权限的
private:
static int m_b;
};
int person::m_a=100;//(类外初始化)
int person::m_b=20;
void test1(){
person p;
cout<<p.m_a<<endl;
person p2;
p.m_a=200;
cout<<p.m_a<<endl;
}
void test2(){
//静态成员变量,不属于某个对象,所有对象共享同一份数据
//1.通过对象名来访问
person p;
cout<<p.m_a<<endl;
//2.通过类名来访问
cout<<person::m_a<<endl;
}
int main(){
test2();
return 0;
}
c++静态成员变量 20220622
最新推荐文章于 2024-10-17 10:27:13 发布