Difference between static member functions and non-static member functions

Data members:

Static data members are part of the class,Shared (static area) for all instances of the class;non-static data members,Each instance of the class has a copy (dynamic zone).

Access to static data members:

Static data members are part of the class,Existed before any instance was produced,Accessed by class name ::static member variable name.

Function members (all in the code area):

Static function members and non-static function members are owned by the class,The object does not have a copy of the function.The fundamental difference between a static member function and a non-static member function is that a non-static function consists of an object name.Or object pointer->call, the compiler will pass this pointer to the function when calling;static member functions have class name ::or object name.Call, the compiler does not pass the this pointer to the function, does not recognize the individual object,Often used to manipulate static data members of a class,To access non-static members of a class, you can implement them through objects.

Memory angle analysis:

The static members (data members and function members) of the class are owned by the class itself,Memory is allocated when the class is loaded,Can be accessed directly by class name;Non-static members (data members and function members) belong to instances of the class,So memory is allocated only when an instance of the class is created,And access through examples.

Note:The static data members of the class are statically stored,It's a static life cycle,Must be initialized.

Note:The initialization of static data members is performed outside the class.Do not add static in front to avoid confusion with general static variables or objects.

Static member functions accessing non-static members error:

Static members of a class already allocate memory when the class loads,At this time, non-static members of the class have not yet allocated memory.Accessing something that doesn't exist in memory will naturally cause an error.


using namespace std;
class test
    test (int a) {a=a;++ b;}
    static void smf (test tt);
    int a;
    static int b;
void test ::smf (test tt)
  cout<"tt.a:"<tt.a<endl;//Refer to non-static members through objects in static member functions
  cout<"test ::b:"<test ::b<endl;
int test ::b=0;//Format of static data member initialization<data type><class name>:::<static data member name>=<value>
int main ()
  test t1 (100);
  test t2 (200);
  test ::smf (t1);
  test ::smf (t2);//static member function call without object name
  system ("pause");
  return 0;
  • Previous Example of jQuery simple title hint effect
  • Next Image cropping based on native JS