静态成员分为静态成员变量和静态成员函数
1.静态成员变量:
- 所有对象共享同一份数据
- 在编译阶段分配内存
- 类内声明,类外初始化
#include
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的值为:"<
//静态成员变量共享同一份数据,因此不属于某个对象上
//所以访问方式有两种
//1.通过对象访问
person p3;
p3.m_age=50;
cout<<"通过对象访问p3的值为:"<
test01();
test02();
return 0;
}
2.静态成员函数
- 所有对象共享同一份函数
- 静态成员函数只能访问静态成员变量
#include
using namespace std;
class person
{
public:
static int a;
int b;
static void func()
{
a=10;//静态成员函数调用静态成员可以
//b=100;不能调用非静态成员变量
cout<<"静态成员函数的调用"<
//1.通过对象访问
person p1;
p1.func();
//2.通过类名访问
person::func();
}
int main()
{
test01();
return 0;
}