This is often the case when writing a program: You need to count the number of all object instances of a class. A simple method is to use a global variable, but its disadvantages are also obvious. Using static members can solve this problem well. Compared with using global variables to use static members, it has the following advantages:
1) Static members are in the scope of the class, which effectively avoids the problem of duplicate names with other global variables.
2) It can be encapsulated. Static members can be private in access control, just like other members.
2) It is easy to see the meaning of the variable and its association with the class. It is a good code style.
Defining and using static members in C ++ is significantly different from defining and using static members in Java and C. I have encountered many errors. Here we will summarize the usage:
1. Description and definition of static members
The declaration of static members is in the class definition body.
Example:
1 class TestClass2 {3 private:4 static int itemCount;5 static int initItemCount();6 };
If you call the static member only in this way, the undefined error will occur. The definition of the static member must be external to the class definition:
1 int TestClass::itemCount = initItemCount();
You do not need to add the static keyword in the definition. The definition of static member functions is the same as that of member variables.
Note that you Cannot initialize static member variables.
Ii. use static members
You can directly use static members within the class:
1 class TestClass2 {3 public:4 TestClass(); ~TestClass();5 static int getItemCount();6 private:7 static int itemCount;8 static int initItemCount();9 };
1 TestClass::TestClass() 2 { 3 itemCount++; 4 } 5 6 int TestClass::itemCount = initItemCount(); 7 8 int TestClass::initItemCount() 9 {10 return 0;11 }12 13 TestClass::~TestClass()14 {15 itemCount--;16 }
Call static members outside the class:
1 #include <iostream> 2 #include "TestClass.h" 3 int main() 4 { 5 TestClass t; 6 TestClass *pt = &t; 7 t.initItemCount(); 8 pt->initItemCount(); 9 TestClass::initItemCount();10 return 0;11 }
3. Const static member variables
The const static member variable must be initialized while being declared.