C++ static member function and static member variable

The role of static member functions

  • Calling this function will not access or modify any object (non-static) data members
  • Can be called without creating an object

Reason:
The static members (variables/methods) of a class belong to the class itself, memory is allocated when the class is loaded, and can be accessed directly through the class name.
Non-static members (variables/methods) belong to the object of the class. Memory is only allocated when the corresponding class is generated (the instantiation of the class is created), and then accessed through the instantiated object of the class.


static member variable

  • Static member variables exist before objects, so static member variables must be initialized outside the class
  • Static member variables are owned by the entire class
  • Shared static member variables can be directly accessed through the class name
  • All objects of the class share the static member variables of the class

static member function

  • The static member function of the class can only access static member variables and static member functions (because it does not accept this pointer, intelligent access to the static member of the class)
  • A public static member function of a class can be accessed by the class name
  • Public static member functions of a class can be accessed by object name
  • Static member functions cannot be modified by virtual, because static members only belong to the class, not to the instantiation of any class, so they have no practical significance.
class mybook
{

public:
    static int width;
    static int page_num;
    static void print()
    {
        cout<<"书本的页数为:"<<page_num<<endl;
    }
};
int mybook::page_num = 10;
int mybook::width = 100;
int main() {
    mybook book1;
    book1.print();
    mybook::page_num = 15;

    book1.print();

    mybook book12;
    book12.print();
    
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_40824135/article/details/128836330