How can i modify variables in static member function?

≡放荡痞女 提交于 2019-12-02 10:13:29

You can pass a pointer to an instance to the method:

class me {
public:
    void X() { x = 1;}
    void Y() { y = 2;}

    static void Z(me* this_) { // fake "this" pointer
      this_->x = 5 ;
      this_->y = 10;
    }

public:
    int x, y;
};


int main() {
    me M;

    M.X();
    M.Y();
    M.Z(&M);  // this works, but
    // usually you call static methods like this
    // me::Z(&M);

    return 0;
}

You have two ways to do it :

  • Define your members as static if they are used in a static method.
  • Implement Dont use of static methods when class's members are non-static

Generally, the memory of static members or methods created once even when you dont create an object of your class. So you cannot use of a non-static members in a static method, because non-static members still have no memory While static methods have memory...

Try this :

public:
   static void X() { x = 1;}
   static void Y() { y = 2;}

public:
   static int x;
   static int y;

Dont forget to initialize static members :

int me::x = 0;
int me:y = 0;

You cannot use of this pointer inside a static method, because this may only be used inside a non-static member function. Notice the following :

this->x = 12;        // Illegal use static `x` inside a static method
me::x = 12;          // The correct way to use of `x` inside a static method
Kaushal Gupta

You are trying to use a non-static member from a static member function. That's why it's giving you an error.

You can fix this by making the member function non-static (by removing static keyword). You could also make the variable static, so that your static member function can access it, but if you do so, the two other functions will still not compile.

Static method can access static members only.

class me {

  public:
void X() { x = 1;}
void Y() { y = 2;}

static void Z() {
  x = 5 ; y = 10;
}

public:
  static int x, y;
};

int main() {
  me M;

  M.X();
  M.Y();
  M.Z();

  return 0;
}

Adding to that @nivpeled said, think about this:

You may create several instances of me on your program. Which ones of the instances the static Z() method should modify?

Please read stackoverflow answer to get a better understanding. Error is due to access of non-static members of the class. Note that this pointer refers only to object instance and only the non-static member function can access them. To make the program work, make the variables as static.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!