In fact, we can intuitively understand that static member functions cannot invoke non-static member variables.
Because both static member functions and static member variables are in the category of classes, and
There is always only one copy of the entire life cycle of a class. Non-static member variables and non-static member functions, however
is for the object of the class.
However, in essence, there is no default this pointer in the function parameter of the static member function of the class, resulting in the inability to
Invokes the member of the specific instance object.
Let's take a look at the following test:
Static member variables are called first in a static member function:
1#include <iostream>2 using namespacestd;3 4 classVpoet5 {6 Public:7 Static intA;8 intb;9 Ten Public: OneVpoet (intdata) A { -b=data; - } the - Static voidstatictestfun1 () - { -cout<<"Static a="<<a<<Endl; + } - }; + A intVpoet::a=Ten; at - intMain () - { -Vpoet *V; -v=NewVpoet (5); - vpoet::statictestfun1 (); in return 0; -}
The call succeeds as follows:
Now let's call the non-static member variable in the static member function:
1#include <iostream>2 using namespacestd;3 4 classVpoet5 {6 Public:7 Static intA;8 intb;9 Ten Public: OneVpoet (intdata) A { -b=data; - } the - Static voidstatictestfun1 () - { -cout<<"Static b="<<b<<Endl; + } - }; + A intVpoet::a=Ten; at - intMain () - { -Vpoet *V; -v=NewVpoet (5); - vpoet::statictestfun1 (); in return 0; -}
The error was prompted under compilation:
The main idea is that the non-static member variable B of a class is referenced in a static member function.
In fact, this can be further analyzed below:
There is no default this pointer in the function parameter of a static member variable to point to the class object itself.
So when we call the object's non-static member variable, it doesn't recognize the variable.
For static member variables, however, they exist throughout the class, for each class object
Common, so even if there is no default this parameter can still recognize the static member variable
A C + + static member function cannot call a non-static member variable