For some classes, we may need to define a global object. For example, we want to define an integer to record the number of calls to a function of a class, or count the total number of objects created for this class. Previously, the global object can only be implemented through a global object, but this has an obvious drawback: The Global object will destroy the class encapsulation feature, and any code can modify this global object, which is very insecure.
Therefore, class static members are introduced in C ++, which are modified using static. It must be clear that a static object is not a member of a class, but a common object of the class. If we set it as a private member, functions outside the class will not be able to access it, thus implementing encapsulation.
Let's first look at a simple program:
class Test{public:Test(){cnt++;}static void display(){cout<<cnt<<endl;}static int cnt;static const int one = 1;};int Test:: cnt = 0;const int Test::one;int main(){Test tst1;tst1.display();Test tst2;tst2.display();tst2.cnt = 10;Test tst3;tst3.display();Test::cnt = 100;Test tst4;tst4.display();cout<<Test::one<<endl;return 0;}
The test class in the program declares a static member CNT, which can be used to record the number of test objects. The first print result is 1, and the second print is 2. because I set it as a public Member, I can modify it outside the class to make it "look" similar to a common member of the class, but after modification, the result of 3rd printing times becomes 11, which indicates that the last modification to the static member of the class still has an impact on the usage of the class. Of course, we can also use the scope OPERATOR: to modify it.
For data, we can define it as static, or for functions. At this time, this function also belongs to a class, rather than a specific object. Therefore, the static member function does not have the this pointer. Of course, static can be completely declared in the class, but in the out-of-class definition, static is added in the declaration, and static is not required in the definition.
Note that static data members must be defined outside the class and can only be defined once. They cannot be initialized through constructors! So it is best to put it in the CPP file of the corresponding header file, that is, put it together with the definition of the member's non-inline function! Its definition method is the same as that of other class members: define the type, specify the class, and finally define the statement. Note that static cannot be added during definition.
The above definition method has a special case, that is, the const static member of the integer type. It is initialized in the class definition body: static const int one = 1; but the initialization here is essentially declared, its definition is still performed outside the class, but it does not need to specify the initial value: const int test: one;