体系结构 x86_64 的未定义符号静态类成员错误

Ran*_*but 2 c++ static x86-64

我不断收到我在这里经常看到的错误代码,但大多数答案似乎都评论了我没有的头文件问题(我不认为?)。sortKey 是一个私有静态成员,我相信我的 setter 和 getter 中出现错误。

 bool Student::setSortKey(int userKey) {
   sortKey = SORT_BY_LAST;
   if(!validSortKey(userKey))
      return false;
   sortKey = userKey;
   return false;
}
static int getSortKey() { return sortKey; }
Run Code Online (Sandbox Code Playgroud)

还有错误...

Undefined symbols for architecture x86_64:
  "Student::sortKey", referenced from:
      Student::setSortKey(int) in main.o
      Student::getSortKey() in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)

我想了一会儿,也想不通到底哪里出了问题。我是否需要使用 Student:: (这是类名)在 setter 中引用 sortKey?类中的所有方法也被定义为静态的。任何帮助将不胜感激。

πάν*_*ῥεῖ 5

假设你有一个像这样的声明

class Student {
    // ...
    static int sortKey;
};
Run Code Online (Sandbox Code Playgroud)

Student::sortKey在您的文件中提供定义.cpp

int Student::sortKey = SORT_BY_LAST;
Run Code Online (Sandbox Code Playgroud)