C++ static关键字

几点总结

1、类内的static成员变量全局可见,需要类内声明,类外初始化

2、static成员函数只能调用static成员变量、static成员函数和类外部的其他函数

3、static成员仍受private关键字限制(private成员函数只能不能主动调用,只能被类内的其他成员函数调用)

例子:

#include <cstdio>
#include <iostream>

using namespace std;

class A{
public:
    static void f1(){
        std::cout << "f1() called" << std::endl;
        f2();
        cout << "===a: " << A::a << endl;
    }
    static int a;
private:
    static void f2(){

        cout << "f2() is called" << endl;
        cout << a << endl;
    }


};

int A::a = 5;


int main()
{
    A::f1();
    cout << "main: " << A::a << endl;
    // A::f2();
}