JiaHeng-DLUT
8/8/2019 - 11:54 AM

static

Static

限定作用域 + 保持变量内容持久化

  1. 静态成员

    #include <iostream>
    using namespace std;
    
    class Box {
    public:
     static int Count;
     Box() {
         Count++;
     }
    };
    
    int Box::Count = 0;
    
    int main(void) {
     Box Box1 = Box();
     Box Box2 = Box();
    
     cout << Box::Count << endl; // 2
    
     return 0;
    }
    
    
  2. 静态成员函数

    • 如果把函数成员声明为静态的,就可以把函数与类的任何特定对象独立开来。
    • 静态成员函数即使在类对象不存在的情况下也能被调用,静态函数只要使用类名加范围解析运算符::就可以访问。
    • 静态成员函数只能访问静态成员数据、其他静态成员函数和类外部的其他函数
    • 静态成员函数有一个类范围,他们不能访问类的 this 指针。您可以使用静态成员函数来判断类的某些对象是否已被创建。
    • 静态成员函数可以继承和覆盖,但无法是虚函数

    静态成员函数与普通成员函数的区别:

    • 静态成员函数没有 this 指针,只能访问静态成员(包括静态成员变量和静态成员函数);
    • 普通成员函数有 this 指针,可以访问类中的任意成员。
    #include <iostream>
    using namespace std;
    
    class Box {
    public:
     static int Count;
     Box() {
         Count++;
     }
     static int getCount();  // 增加了类的访问权限的全局函数
    };
    
    // 实现的时候不需要 static,因为 static 是声明性关键字
    int Box::Count = 0;
    
    int Box::getCount() {
     return Count;
    }
    
    int main(void) {
     cout << Box::getCount() << endl;    // 0
    
     Box Box1 = Box();
     Box Box2 = Box();
    
     cout << Box::getCount() << endl;    // 2
    
     return 0;
    }
    
    
  3. 只在 cpp 内有效的全局变量 static int val = 0;

    • 这个变量的含义是该 cpp 内有效,其他的 cpp 文件不能访问这个变量
    • 如果有两个 cpp 文件声明了同名的全局静态变量,那么他们实际上是独立的两个变量;
  4. 只在 cpp 内有效的全局函数

    • 函数的实现使用 static 修饰,那么这个函数只可在本 cpp 内使用,不会同其他 cpp 中的同名函数引起冲突;
    • 不要在头文件中声明 static 的全局函数,不要在 cpp 内声明非 static 的全局函数,如果你要在多个 cpp 中复用该函数,就把它的声明提到头文件里去,否则 cpp 内部声明需加上 static 修饰;

References