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

Bah*_*ast 1 c++ static-methods class class-members

我有下面的代码,我想修改静态函数中类的变量,但有一些错误。\n我如何用“this”指针修复它?

\n\n

类中的静态成员无法访问“this”指针,另一方面,我试图访问静态成员函数中的类变量,因此我正在寻找一种使用类“this”指针的方法我”来做到这一点。

\n\n
class me {\n  public:\n     void X() { x = 1;}\n     void Y() { y = 2;}\n\nstatic void Z() {\n  x = 5 ; y = 10;\n}\n\npublic:\n  int x, y;\n};\n\nint main() {\n  me M;\n\n  M.X();\n  M.Y();\n  M.Z();\n\n  return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我懂了error

\n\n
\n

在静态成员函数中无效使用成员 \xe2\x80\x98me::x\xe2\x80\x99。

\n
\n

Bat*_*ted 6

您有两种方法可以做到这一点:

  • 定义您的成员,就像static它们在方法中使用一样static
  • 实施 当成员存在时不要使用static方法class'snon-static

一般来说,成员的内存staticmethods创建一次,即使您不创建class. non-static所以你不能在方法中使用成员static,因为non-static成员仍然没有内存,而static方法有内存......

尝试这个 :

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

public:
   static int x;
   static int y;
Run Code Online (Sandbox Code Playgroud)

不要忘记初始化static成员:

int me::x = 0;
int me:y = 0;
Run Code Online (Sandbox Code Playgroud)

不能在方法this内部使用指针static,因为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
Run Code Online (Sandbox Code Playgroud)


use*_*087 5

您可以将指向实例的指针传递给该方法:

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;
}
Run Code Online (Sandbox Code Playgroud)