为什么在尝试在类中设置静态变量时会出现链接器错误?

rsk*_*k82 1 c++ static class undefined-reference

可能重复:类中的
静态成员变量
什么是未定义的引用/未解析的外部符号错误以及如何修复它?

class test_struct {
  static int number;
 public:
  static void set() {
    number = 42;
  }
};

int main() {
  test_struct::set();
}
Run Code Online (Sandbox Code Playgroud)

错误是:

[...]Temp\ccGGxEAz.o:test.cpp:(.text.startup+0xf): undefined reference to `test_struct::number'
collect2.exe: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

bil*_*llz 5

test_struct::number在使用之前,您需要在源代码(.cpp)中定义静态成员:

class test_struct {
  static int number;
 public:
  static void set() {
    number = 42;
  }
};

int test_struct::number = 0;
Run Code Online (Sandbox Code Playgroud)