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

时间:2013-01-29 12:25:26

标签: c++ linker operator-overloading

我在chess_location.h中定义了以下函数:

inline chess_location operator+(chess_location lhs, const chess_coord& rhs);

然后,在chess_location.cpp

#include "chess_location.h"

chess_location operator+(chess_location lhs, const chess_coord& rhs) { 
  //function definition
}

然后我在main()的{​​{1}}中使用此运算符,如下所示:

main.cpp

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

#include "chess_location.h"
int main() {
  chess_location_B = chess_location_A + chess_coord;
}

在我看来,链接器没有将运算符的声明连接到定义,但我不确定为什么。我怀疑我的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 可能有问题。但是,如果我将运算符定义移动到const,则所有内容都会编译并正常工作。

知道这个错误来自何处?

1 个答案:

答案 0 :(得分:7)

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

相关问题