未定义的静态变量c ++引用

Too*_*bal 60 c++ static

您好我在以下代码中得到未定义的引用错误:

class Helloworld{
  public:
     static int x;
     void foo();
};
void Helloworld::foo(){
     Helloworld::x = 10;
};
Run Code Online (Sandbox Code Playgroud)

我不想要一个static foo()功能.如何static在类的非static方法中访问类的变量?

And*_*owl 90

我不想要一个static foo()功能

那么,foo()不是在你的类静态的,你就不会需要使它static以访问static类的变量.

您需要做的只是为静态成员变量提供定义:

class Helloworld {
  public:
     static int x;
     void foo();
};

int Helloworld::x = 0; // Or whatever is the most appropriate value
                       // for initializing x. Notice, that the
                       // initializer is not required: if absent,
                       // x will be zero-initialized.

void Helloworld::foo() {
     Helloworld::x = 10;
};
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢。我正在实例化HelloWorld :: x,但没有使用int实例化。再次感谢。 (3认同)

Pet*_*ker 52

代码是正确的,但不完整.该类Helloworld具有其静态数据成员的声明x,但没有该数据成员的定义.有些你需要的源代码

int Helloworld::x;
Run Code Online (Sandbox Code Playgroud)

或者,如果0不是合适的初始值,则添加初始值设定项.


pvc*_*pvc 26

老问题,但是;

由于c++17您可以在不需要定义的情况下声明static成员inline并在其中实例化它们:classout-of-class

class Helloworld{
  public:
     inline static int x = 10;
     void foo();
};
Run Code Online (Sandbox Code Playgroud)