静态成员分为静态成员变量和静态成员函数
1.静态成员变量:
- 所有对象共享同一份数据
- 在编译阶段分配内存
- 类内声明,类外初始化
#include<iostream>
using namespace std;
class person
{
public:
static int m_age;
private:
static int m_B;
};
int person:: m_age=100;
int person::m_B=1000;
void test01()
{
person p1;
cout<<"p1的值为:"<<p1.m_age<<endl;
person p2;
p2.m_age=200;
cout<<"p2的值为:"<<p1.m_age<<endl;
}
void test02()
{
person p3;
p3.m_age=50;
cout<<"通过对象访问p3的值为:"<<p3.m_age<<endl;
cout<<"通过类名访问的值为:"<<person::m_age<<endl;
}
int main()
{
test01();
test02();
return 0;
}
2.静态成员函数
- 所有对象共享同一份函数
- 静态成员函数只能访问静态成员变量
#include<iostream>
using namespace std;
class person
{
public:
static int a;
int b;
static void func()
{
a=10;
cout<<"静态成员函数的调用"<<endl;
}
};
int person::a=0;
void test01()
{
person p1;
p1.func();
person::func();
}
int main()
{
test01();
return 0;
}