关键字static

修饰变量

静态变量存储在静态存储区,只初始化一次,未初始化时默认值为0。

全局静态变量:只能在本文件内使用
局部静态变量:每次调用都不重新初始化。

void TestStaticLocalVar() {
    static int data;
    data+=1;
    std::cout<<__FUNCTION__<<":"<<data<<std::endl;
}

void loop() {
    for(int i=0;i<5;i++) {
        TestStaticLocalVar();
    }
}

修饰函数

static修饰的函数只能在本文件中使用,不能在其他文件中使用。函数默认属性是extern

修饰类成员变量、类成员函数

static类成员变量属于类,不属于类对象。必须在类外部初始化,存储在静态存储区
static类成员函数没有this指针,不能为虚函数。可以直接调用(只能访问 static修饰的类成员变量和函数,不能访问非static的类成员变量和函数)

class A
{
public:
    static int data_static;

    static void show_static() {
        std::cout<<__FUNCTION__<<":"<<data_static<<std::endl;
        //data=1;//error:不能访问非static成员变量
        //show();//error:不能访问非static成员函数
    }

     A() {

     }

    ~ A() {

    }  
};

int A::data_static=100;//必须初始化

void TestClassStatic() {
    A::show_static(); //直接调用
}

原文地址:https://www.cnblogs.com/smallredness/p/11065261.html