如何修改静态成员函数中的变量? [英] How can i modify variables in static member function?
本文介绍了如何修改静态成员函数中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在下面有一个代码,我想在静态函数中修改类的变量,但是有一些错误.我该如何使用"this"指针对其进行修复?
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?
对于类中的静态成员,无法访问"this"指针,另一方面,我正在尝试对Static成员函数中的类变量进行访问,因此,我正在寻找一种使用"this"指针的方法属于我"类的人.
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;
}
我遇到了这个错误
:
在静态成员函数中无效地使用了成员"me :: x".
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;
}
这篇关于如何修改静态成员函数中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文