First, define the following class A:
Class A{private: static int val_s;public: static int getval () {cout << "call Getval in A ..." << endl;re Turn val_s;}};
As we can see, the definition of the above class contains static member variables val_s and static member functions Getval (), for static member variables, it is generally declared as non-public, which means that if you need to access the member variable outside the class, we need to provide a member function interface. Static member variables, on the other hand, are independent of the class's object and are part of the shared object of all classes, which means that if there is one such function to manipulate the static member variable, then the function is not implied by the this pointer, This is not the same as the General member function (the general member function has this pointer), so the static member function comes into being.
It is worth noting that such a static member function must meet the following requirements:
1 cannot manipulate non-STAITC member variables
2 cannot be declared as const, volatile, or virtual.
3 does not need to be called through the object of the class. (although it is also legal to invoke the object of the Class).
#include <bits/stdc++.h>using namespace Std;class a{private: static int val_s;public: static int Getval ( {cout << "call Getval in A ..." << Endl;return val_s;}}; int a::val_s = 4;int Main (void) { cout << ((A *) 0)->getval () << Endl; Constructs a temporary object to invoke the static function A; cout << a.getval () << Endl; Access cout << a::getval () << Endl through the object of the class; Access to return 0 through the scope of the class ;}
In fact, when the compiler is facing a static member function, it is called by the member function as a global function, just as the compiler handles the Non-member member function. (It also uses name mabgling to change the declaration of the member function to be unique as a global non-member function.)
Static member functions of C + + function calls