In C + +, a static member is an entire class rather than an object, and a static member variable stores only one copy for all objects to be shared. So it can be shared across all objects. Using static member variables to implement data sharing between multiple objects does not break the principle of shadowing, guaranteeing security and saving memory.
The owner of a static member is the class itself and the object, but multiple objects have the same static members. Thus, when defining an object, it cannot be initialized by a constructor function; A static member cannot be initialized inside a class definition, but only outside of class body; Static variables still conform to public, private, protect characteristics; A static member function does not have the this pointer, and it cannot return a non-static member because the class itself can be called, in addition to the object calling it.
a static variable
1. Static variables must be defined and assigned externally
A, cannot be defined in the main () function
b, cannot be defined in the constructor of a class
2, you must define a static variable, otherwise the variable has no memory space (the class is only declared)
3. The class itself can call static variables directly
4, static variables still conform to public, private, protect characteristics
two static methods
1, the static method can be called directly by the class, but same as the static variable with public, private, protect characteristics
2. Static member functions cannot invoke non-static members of a class. Because the static member function does not contain the this pointer.
3. Static member functions cannot be declared as virtual or Postfix const functions at the same time. Because virtual is used to distinguish which object is calling him, it contradicts the static method. The suffix const is used to modify the this pointer, and the static variable does not contain the this pointer.
A, can not be declared at the same time as virtual
B, cannot be declared as Postfix const at the same time
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Considerations for static variables and static methods in C + + classes