[C++] Static modifies member variable member function in class

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


1. Definition:

Class members declared static are called static members of the class, member variables modified with static are called static member variables; member functions modified with static are called static member functions. Static member variables must be initialized outside the class

2. Features:

1. Static members are shared by all class objects, do not belong to a specific object, and are stored in the static area

insert image description here

2. Static member variables must be defined outside the class. The static keyword is not added when defining, and only declared in the class

insert image description here

It is a privilege for static member variables. The private ones are just declarations and do not create space, and our static member variables are shared by all classes and do not belong to a certain class, so they must be defined outside the class.

3. Class static members can be accessed with class name:: static member or object. static member

insert image description here

4. Static member functions have no hidden this pointer and cannot access any non-static members

We know that the normal member functions in the class will pass a hidden this pointer of type (A* const this) , so that the member variables in the private we use in the function are actually this, but the static member functions are all What is shared by classes does not belong to a specific class, so there is no hidden this pointer.
insert image description here

5. Static members are also members of the class, subject to the restrictions of public, protected, and private access qualifiers

3 questions:

1. Can a static member function call a non-static member function?

Can't. Non-static member function calls need this pointer, he does not have this

2. Can a non-static member function call a static member function of a class?

Yes, my static member function is in the static area, and anyone can call it.

3. Design a class that can only create objects on the stack or heap outside the class

insert image description here

4. Summary:

  1. Static members are shared by all class objects, do not belong to a specific object, and are stored in the static area
  2. Static member variables must be defined outside the class, the static keyword is not added when defining, and only declared in the class
  3. Class static members can be accessed with class name:: static member or object. static member
  4. Static member functions do not have a hidden this pointer and cannot access any non-static members
  5. Static members are also members of classes, subject to public, protected, private

Guess you like

Origin blog.csdn.net/m0_74774759/article/details/130912030