运算符过载的未解析外部符号

Fab*_*amp 1 c++ linker operator-overloading

我已经定义了以下函数chess_location.h:

inline chess_location operator+(chess_location lhs, const chess_coord& rhs);
Run Code Online (Sandbox Code Playgroud)

然后,在chess_location.cpp:

#include "chess_location.h"

chess_location operator+(chess_location lhs, const chess_coord& rhs) { 
  //function definition
}
Run Code Online (Sandbox Code Playgroud)

然后在我的main()in中使用此运算符main.cpp,如下所示:

#include "chess_location.h"
int main() {
  chess_location_B = chess_location_A + chess_coord;
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到链接器错误,说无法找到运算符:

error LNK2019: unresolved external symbol "class chess_location __cdecl operator+(class chess_location,class chess_coord const &)" (??H@YA?AVchess_location@@V0@ABVchess_coord@@@Z) referenced in function _main
Run Code Online (Sandbox Code Playgroud)

在我看来,链接器并没有将运算符的声明连接到定义,但我不确定为什么.我怀疑我的身体可能有问题const.main.cpp但是,如果我将运算符定义移动到,则所有内容都会编译并正常工作.

知道这个错误来自何处?

Wer*_*nze 7

如果operator +应该是内联的,那么您需要将定义放在头文件中.如果它不是内联的,那么将它放在cpp文件中并从声明中删除"inline".