静态成员就是在成员变量和成员函数前加上关键字static 称为静态成员
也是有访问权限的 需要类内声明 类外初始化
[] [c++]1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| #include<bits/stdc++.h> using namespace std;
class Person { public: //所有对象共享同一份数据 //编译阶段就分配内存 //类内声明 类外初始化操作 static int m_A; };
int Person::m_A=100;
void test01() { Person p; cout<<p.m_A<<endl;//100 Person p2; p2.m_A=200; cout<<p.m_A<<endl;//200 }
void test02() { //静态成员变量不属于某个对象上 所有对象共享同一份数据 //因此静态变量有两种方式访问 //1.通过对象 Person p; cout<<p.m_A<<endl; //2. 通过类名 cout<<Person::m_A<<endl; Person::m_A=200; cout<<Person::m_A<<endl; }
int main() { //test01(); test02(); }
|
静态成员函数
[] [c++]1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include<bits/stdc++.h> using namespace std;
//静态成员函数 //所有对象共享同一个函数 //静态成员函数只能访问静态成员变量 class Person { public://静态函数有访问权限 static void func() //声明 { m_A=100; //静态成员函数可以访问静态成员变量 //m_B=100; 无法访问 cout<<"static void func的调用" <<endl; } static int m_A; //类内声明 类外初始化 int m_B; } ; int Person::m_A=0; void test01() { //1.通过对象访问 Person p; p.func(); //2.通过类名访问 Person::func(); }
int main() { test01(); return 0; }
|