操作符过载问题

Operator overload problems

本文关键字:问题 操作符      更新时间:2023-10-16

在person.h中,在名为person的类的公共部分下,我有如下内容:

bool operator < (person& currentPerson);

In 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 &)" (??Mperson@@QAE_NABV0@@Z) referenced in function "class person __cdecl max(class person &,class person &)" (?max@@YA?AVperson@@AAV1@0@Z)
1>c:userskennethdocumentsvisual studio 2012ProjectsFunctionTemplatesDebugFunctionTemplates.exe : fatal error LNK1120: 1 unresolved externals

在代码的某个地方,当使用函数max时,您正在将一个人与临时人员进行比较。要做到这一点,你需要接受const引用。

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

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