In C ++, when a static member function accesses a non-static member variable, first look at a classclass
{
Public:
Static functiona ()
{
Menber = 1;
}
PRIVATE:
Int menber;
}
An error occurred while compiling the above Code. The reason is simple. As we all know, static member functions cannot access non-static members. This is because static functions belong to Classes rather than the entire object, and member in static functions may not be allocated memory. The static member function does not have an implicit this independent variable. Therefore, it cannot access non-static members of its own class. (I have read a good article "This pointer in C ++" to introduce the details of this aspect)
What should I do if I want to access it? Everyone on Earth knows that as long:
Int menber;
// Change the line above:
Static int menber;
However, this method forces us to convert all the member variables used in the static function into static ones, and the static members must be explicitly initialized. Is there a better way? The answer is yes. Code statement:
Class
{
Public:
Static functiona (A * _)
{
_ A-> menber = 1;
Cout <_ A-> menber <Endl;
_ A-> F ();
}
Void F ()
{
Cout <"f called" <Endl;
}
PRIVATE:
Int menber;
};
The premise is that the class has to allocate memory space. In fact, what I do here is to use an object pointer as the "This" pointer of a static member function, it is intended to simulate the transfer of this variable in non-static member functions (this pointer exists in non-static member functions (push seems to be in ECx ))
This idea is generated when createthread is required in a class, because the thread funtion requires static (yes? I don't know why the code I wrote is static. I forgot where I saw this requirement. Find the reason ).
It can be seen that C ++ is very flexible.