I have a code below, i want to modify class's variables in static function but there is some error. How can i fix it with "this" pointer?
There is no access to "this" pointer for static members in class,on the other hand I am trying to make an access to class variables in Static member function, therefore i am looking for a way to use "this" pointer of class "me" to do it.
class me {
public:
void X() { x = 1;}
void Y() { y = 2;}
static void Z() {
x = 5 ; y = 10;
}
public:
int x, y;
};
int main() {
me M;
M.X();
M.Y();
M.Z();
return 0;
}
I got this error :
invalid use of member ‘me::x’ in static member function.
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
staticif they are used in astaticmethod. - Implement Dont use of
staticmethods whenclass'smembers arenon-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
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.
来源:https://stackoverflow.com/questions/57070060/how-can-i-modify-variables-in-static-member-function