2013-04-15 82 views
0

在person.h,在一类名为人的公共部分,我有这样的:运算符重载问题

bool operator < (person& currentPerson); 

在person.cpp我有这样的:

bool person::operator < (person& currentPerson) 
{ 
    return age < currentPerson.age; 
} 

当我编译我得到一个链接器错误,但只有当我真的使用操作符。 有人能告诉我我做错了什么吗?

这是错误消息。

1>FunctionTemplates.obj : error LNK2019: unresolved external symbol "public: bool __thiscall person::operator<(class person const &)" ([email protected]@[email protected]@Z) referenced in function "class person __cdecl max(class person &,class person &)" ([email protected]@[email protected]@[email protected]@Z) 
1>c:\users\kenneth\documents\visual studio 2012\Projects\FunctionTemplates\Debug\FunctionTemplates.exe : fatal error LNK1120: 1 unresolved externals 
+0

你如何使用运营商,什么是'person'(右操作数)对象你与它使用的类型? – 0x499602D2

+0

尝试使用'const'将签名更新为'bool operator <(const person&currentPerson);'? – billz

回答

1
在你的代码

某处,使用功能max时,你是一个临时的人比较的人。为了这个工作,你需要采用const引用。

bool operator < (const person& currentPerson) const; 
       ^^^^       ^^^^^^ //This wont hurt too 

bool person::operator < (const person& currentPerson) 
//      ^^^^^ 
{ 
    return age < currentPerson.age; 
} 
+0

是什么让这个人变成临时的?人物对象都不是常量。 – kennycoc

+0

你并没有把它们声明为常量。但有时STL算法会创建临时对象。例如,除非运算符函数接受const引用,否则'p stardust

+0

这就解决了问题,我想知道为什么我原来有错的更多信息 – kennycoc