C ++ static member variables and static member functions

1. Static member functions

  1. The member function declaration is static. The function declaration must include static, but it is not required in the definition. But it can also be defined at the time of declaration.
  2. It is not possible to call a member function through an object, so you cannot use the this pointer, only call it through the class name and scope resolver.
  3. Static member functions can only access static data members

2. Static member variables

  1. Static member variable is a special member variable, which is modified by the keyword static .
  2. Static member variables can only be initialized outside the class. The memory of static member variables is not allocated when the class is declared or when the object is created, but when (outside the class) is initialized. Conversely, static member variables that are not initialized outside the class cannot be used.
  3. Static member variables do not occupy the memory of the object, but open up memory outside all objects, even if the object is not created.
  4. Three methods for accessing static member variables:
    either through an object, through a class, or through an object
//通过类类访问 static 成员变量
Student::m_total = 10;
//通过对象来访问 static 成员变量
Student stu("小明", 15, 92.5f);
stu.m_total = 20;
//通过对象指针来访问 static 成员变量
Student *pstu = new Student("李华", 16, 96);
pstu -> m_total = 20;
Published 9 original articles · liked 0 · visits 253

Guess you like

Origin blog.csdn.net/a_465240/article/details/104587698