In depth analysis of static members of C++ classes

  • 2020-04-02 01:43:52
  • OfStack

In C++, a static member is a member of the class rather than an object, and a static member variable stores only one copy for all objects to share. So it can be Shared across all objects. Using static member variables to share data between multiple objects does not break the principle of hiding, ensuring security and saving memory.

Static member is defined or declared with a key static. Static members can be used with a double colon < The name of the class > : : < Static member name > .

In C++ class static member variables and static member functions are prone to error, this article through a few examples to summarize the use of static member variables and member functions, and then give an example to deepen the impression. Hopefully reading this article will give you a better understanding of static member variables and member functions of a class.

The first example calls both static and non-static member functions by class name


class Point
{
public:    
       void init()
       {  
       }
       static void output()
       {
       }
};
void main()
{
       Point::init();
       Point::output();
}

Error C2352: 'Point::init' : illegal call of non-static member function
Conclusion 1: you cannot call a class's non-static member function by its class name.
 
The second example calls both static and non-static member functions through the object of the class
Change the main() of the above example to:

void main()
{
       Point pt;
       pt.init();
       pt.output();
}

Compile passed.
Conclusion 2: class objects can use both static and non-static member functions.
 
The third example USES non-static members of a class in a static member function of the class

#include <stdio.h>
class Point
{
public:    
       void init()
       {  
       }
       static void output()
       {
              printf("%dn", m_x);
       }
private:
       int m_x;
};
void main()
{
       Point pt;
       pt.output();
}

Error C2597: illegal reference to data member 'Point::m_x' in a static member function
Because the static member function belongs to the entire class, it allocates space before the class instantiates the object, and the non-static member of the class must have memory space after the class instantiates the object, so the call goes wrong, like using a variable in advance without declaring it.
Conclusion 3: non-static members cannot be referenced in static member functions.
 
The fourth example USES the static members of a class in its non-static member functions

class Point
{
public:    
       void init()
       {  
              output();
       }
       static void output()
       {
       }
};
void main()
{
       Point pt;
       pt.output();
}

Compile passed.
Conclusion 4: non-static member functions of a class can be called with static member functions, but not vice versa.

The fifth example USES static member variables of a class

#include <stdio.h>
class Point
{
public:    
       Point()
       {  
              m_nPointCount++;
       }
       ~Point()
       {
              m_nPointCount--;
       }
       static void output()
       {
              printf("%dn", m_nPointCount);
       }
private:
       static int m_nPointCount;
};
void main()
{
       Point pt;
       pt.output();
}

Press Ctrl+F7 to compile without errors, press F7 to generate EXE program times link error
Error LNK2001: unresolved external symbol "private: static int Point::m_nPointCount" (? M_nPointCount @ Point @ @ 0 ha)

This is because the class's static member variables must be initialized before they can be used.
Int Point::m_nPointCount = 0;
Recompile the link without errors, run the program will output 1.
Conclusion 5: static member variables of a class must be initialized before they are used.
 
Combined with the above five examples, the static member variables and member functions of the class are summarized:
one A non-static member cannot be called in a static member function.

two A static member can be called in a non-static member function. Because static members belong to the class itself and exist before the objects of the class are generated, static members can be called in non-static member functions.

3. Static member variables must be initialized before they can be used (such as int MyClass::m_nNumber = 0;) Otherwise you will make an error in linker.

Another example of using static member variables and functions of a class to deepen the understanding, this example creates a student class, each object of the student class will constitute a bidirectional linked list, with a static member variable to record the bidirectional linked list of the header, a static member function output the bidirectional linked list.


#include <stdio.h>
#include <string.h>
const int MAX_NAME_SIZE = 30;  

class Student  
{  
public:  
    Student(char *pszName);
    ~Student();
public:
       static void PrintfAllStudents();
private:  
    char    m_name[MAX_NAME_SIZE];  
    Student *next;
       Student *prev;
    static Student *m_head;
};  

Student::Student(char *pszName)
{  
    strcpy(this->m_name, pszName);

       //Creates a two-way linked list where new data is inserted from the top of the list.
    this->next = m_head;
       this->prev = NULL;
       if (m_head != NULL)
              m_head->prev = this;
    m_head = this;  
}  

Student::~Student ()//The destructive process is the process of node disengagement & NBSP;
{  
       if (this == m_head) //This node is the header node.
       {
              m_head = this->next;
       }
       else
       {
              this->prev->next = this->next;
              this->next->prev = this->prev;
       }
}  

void Student::PrintfAllStudents()
{
       for (Student *p = m_head; p != NULL; p = p->next)
              printf("%sn", p->m_name);
}

Student* Student::m_head = NULL;  

void main()  
{   
       Student studentA("AAA");
       Student studentB("BBB");
       Student studentC("CCC");
       Student studentD("DDD");
       Student student("MoreWindows");
       Student::PrintfAllStudents();
}

The program will output:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201309/201309290843112.jpg ">

Of course, in this example, we can add a static member variable to represent the number of students in the linked list. If you are interested, please use this as an exercise.


Related articles: