下面有一段代码,我想在静态函数中修改类的变量,但是有一些错误。 我怎样才能用“这个”指针修复它?
类中的静态成员无法访问“this”指针,另一方面,我试图在静态成员函数中访问类变量,因此我正在寻找一种使用“this”指针的方法类“我”来做这件事。
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;
}
我遇到了这个错误
:
invalid use of member ‘me::x’ in static member function.
最佳答案
您有两种方法可以做到这一点:
- 如果成员在
static
方法中使用,则将它们定义为static
。 - 当
类的
成员是非静态
时,不要使用static
方法
通常,即使您没有创建类
的对象,static
成员或方法
的内存也会创建一次。所以你不能在 static
方法中使用 non-static
成员,因为 non-static
成员仍然没有内存,而 static
方法有内存...
试试这个:
public:
static void X() { x = 1;}
static void Y() { y = 2;}
public:
static int x;
static int y;
不要忘记初始化 static
成员:
int me::x = 0;
int me:y = 0;
您不能在 static
方法中使用 this
指针,因为 this
只能在 non-static< 中使用
成员函数。注意以下几点:
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
关于c++ - 如何修改静态成员函数中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57070060/