About C++ static member functions accessing non static member variables

  • 2020-04-02 01:46:54
  • OfStack


class a
{
public:
  static FunctionA()
  {
     menber = 1;
  }
private:
  int menber;
}

Error compiling above code. The reason is very simple, you know, static member functions can't access non-static members, this is because the static function belongs to the class rather than the entire object, static function members may not allocate memory. Static member functions have no implicit this argument. As a result, it cannot access non-static members of its own class.

What about the visit? Everyone on earth knows that as long as:


int menber;
//change the line above to:
static int menber;

But this method makes us have to make all the member variables used in the static function static, and the static members have to be initialized explicitly, is there a better way? The answer is yes. Code speak:

class a
{
public:
  static FunctionA(a* _a)
  {
    _a-> menber = 1;
 cout<<_a-> menber<<endl;
 _a->f();
  }
void f()
{
 cout<<"f Is called the "<<endl;
}
private:
  int menber;
};

The premise is that the class allocates memory space. What I'm actually doing here is taking an object pointer as a "this" pointer to a static member function, which is intended to mimic passing the this variable in a non-static member function.

This idea came to me when I was trying to create ethread in a class, because Thread's funtion is supposed to be static. I don't know why I wrote code Thread that's static. I don't remember where I saw this requirement. Have time to find out why.

So C++ is very flexible.


Related articles: