c++ - 如何修改静态成员函数中的变量?

标签 c++ class static-methods class-members

下面有一段代码,我想在静态函数中修改类的变量,但是有一些错误。 我怎样才能用“这个”指针修复它?

类中的静态成员无法访问“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/

相关文章:

python - 如何在 Python 中创建新的未知或动态/扩展对象

java - 类的静态方法之间的同步

c++ - 与 whole-archive 和 no-whole_archive 选项的链接问题

c++ - 类成员值被前一个成员覆盖

c++ - 资源管理器

具有多个类的 C++ 新对象

java - 静态方法是 DI 反模式吗?

c# - 使用 TypeMock 验证是否未调用具有特定参数的方法

c++ - 在多重继承中调用构造函数初始化列表中的 sizeof

c++ - 使用 libcurl 和 C++ 将从 IMAP 服务器下载的电子邮件保存到文件中