What are the uses of the “static” keyword in C++?

In C++, the static keyword serves several purposes:

  1. Static member variables are those declared with the ‘static’ keyword. They belong to the class rather than any specific object, meaning that all objects of the class share the same value of the static member variable. Static member variables allow data to be shared between instances of the class. They can be initialized either outside or inside the class.
class MyClass {
public:
    static int count;
};

int MyClass::count = 0;

int main() {
    MyClass obj1;
    MyClass obj2;
    obj1.count = 5;
    obj2.count = 10;
    std::cout << obj1.count << std::endl;  // 输出10
    std::cout << obj2.count << std::endl;  // 输出10
    return 0;
}
  1. Static member functions, declared using the static keyword, are referred to as static member functions. They are called on the class’s objects rather than on specific instances. Static member functions cannot access non-static member variables and can only access static member variables.
class MyClass {
public:
    static void print() {
        std::cout << "Hello, World!" << std::endl;
    }
};

int main() {
    MyClass::print();  // 输出Hello, World!
    return 0;
}
  1. Static local variables are variables declared within a function using the static keyword. They are initialized the first time the function is called and retain their value even after the function has finished executing, until the program ends. Their scope is limited to the function in which they are declared.
void foo() {
    static int count = 0;
    count++;
    std::cout << count << std::endl;
}

int main() {
    foo();  // 输出1
    foo();  // 输出2
    foo();  // 输出3
    return 0;
}
  1. The static keyword can also be used to modify the visibility of functions and variables. By adding the static keyword in front of a function or variable, their visibility can be limited to the current file, avoiding conflicts with functions or variables of the same name in other files. This usage is typically seen in functions or variables in header files to prevent redefinition errors.
bannerAds