How to understand the static member variables and static member functions of C++ class
This article introduces the knowledge of "how to understand the static member variables and static member functions of C++ class". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations! I hope you can read it carefully and be able to achieve something!
1. Static member variables of the class
The static member variables of the C++ class mainly have the following characteristics:
1. Static member variables need to be defined within the class and initialized outside the class.
two。 Static member variables do not depend on the class, static member variables belong to the global area, not to the space of the class.
3. Static member variables can be accessed through class names or objects. Different objects of the same class and static members share the same data.
The following three statements are verified by code:
# include using namespace std;class Base {public: static int val1; / / in-class definition and out-of-class initialization. If the compiler initializes directly, it will report an error int val2;private: static int val3;}; int Base::val1 (1); / / out-of-class initialization, accessing the static member int Base::val3 (2) through the class name / / initialization outside the class. Even private attributes can access the static member int main () {Base base1; Base base2; base1.val1 = 10; base2.val1 = 11; cout through the class name.