Define static variables in member functions
The local variables in the member functions can be static. If you define a local variable in a member function as a static variable, all objects in the class will share the variable when calling this member function.
Example 3-40
In this example, a static variable S is defined in the member function M. Because S is defined in the block, it has the block range, so it can only be accessed within M. S is added each time M is called. Because M is a member function of C, all objects in C share this static local variable. In this way, each call to M accesses the same S. On the contrary, for non-static local variable X, each c object has an X. Therefore, in Main, call c1.m () for the first time to increase s from 0 to 1, call c2.m () to increase s from 1 to 2, and call c2.m () for the second time () increase s from 2 to 3.
In addition:
This variable exists until the end of the program and is not re-generated every call. Static variables in the function are a good implementation method in singleton mode.