Static member functions cannot access non-static members because static functions belong to the class rather than the entire object, and member in the static function may not have memory allocated. The static member function does not have an implied this argument. Therefore, it cannot access the non-static member code of its own class as follows:
Class A
{
Public
Static Functiona ()
{
Menber = 1;
}
Private
int menber;
}
Compile the above code, error. The reason is simple. As you know, static member functions cannot access non-static members because static functions belong to the class rather than the entire object, and member in the static function may not have allocated memory. The static member function does not have an implied this argument. Therefore, it cannot access the non-static members of its own class.
What if you want to visit? All the people of the Earth know as long as:
Copy CodeThe code is as follows:
int menber;
Change the line above to:
static int menber;
But this method allows us to change the member variables used in the static function into static, and the static members have to be explicitly initialized, is there a better way? The answer is yes. Code to speak:
Copy CodeThe code is as follows:
Class A
{
Public
Static Functiona (* _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 allocates memory space. In fact, what I do here is to use an object pointer as the "This" pointer to a static member function, which is intended to mimic the pass of the this variable in a non-static member function (this pointer appears in a non-static member function (push in ECX))
This idea was created when I wanted to createthread in a class, because the funtion of thread was called static. I do not know why I write the code,thread are static. I forgot where I saw the request. Have time to find out why).
Visible C + + is very flexible.
Questions about C + + static member functions accessing non-static member variables