Copy Code code as follows:
Class A
{
Public
Static Functiona ()
{
Menber = 1;
}
Private
int menber;
}
There was an error compiling the above code. The reason is simple, as you all know, static member functions cannot access non-static members because static functions belong to the class and not to the entire object, and members in static functions may not have memory allocated. A static member function has no implied this argument. As a result, it cannot access non-static members of its own class.
What do you do if you want to visit? Earth people know that as long as they will:
Copy Code code as follows:
int menber;
Change the line above to:
static int menber;
But this approach allows us to make the member variables used in the static function static, and the static members have to be explicitly initialized, is there a better way? The answer is yes. Code to speak:
Copy Code code as follows:
Class A
{
Public
Static Functiona (A * _a)
{
_a-> menber = 1;
Cout<<_a-> menber<<endl;
_a->f ();
}
void F ()
{
cout<< "F was called" <<endl;
}
Private
int menber;
};
The premise is that this class has to allocate memory space. What I'm actually doing here is to use an object pointer as the "This" pointer to a static member function, which is intended to mimic passing the this variable in a Non-static member function (which in a Non-static member function appears to be in ecx).
The idea was created when I had to createthread in a class, because the thread funtion was all about static. I don't know why I wrote the Code,thread is static. Forgot where to see the request. Have time to find out why).
Visible C + + is very flexible.