c++ - 与函数一起使用时运算符 > 不匹配

标签 c++ operator-overloading

我重载了以下大于操作符:

bool operator > (Person & a, Person & b)
{
   //firstname is a string data type
   return (a.FirstName > b.FirstName);      
}

如果我有类似下面的东西,哪个工作正常:

Person a = myPersonA;
Person b = myPersonB;

return myPersonA > myPersonB;

但是,在我的 Person 类中,我定义了一个 Person getByID(int id) 函数,它通过给定的 ID 返回一个 Person 的实例。如果我尝试将我的运算符与此函数的返回值一起使用,如下所示:

bool whosGreater = listPeople.getById(1) > listPeople.getById(2);

我收到 “错误:运算符不匹配 >(Person&, Person&)”

但如果我执行以下操作,它会正常工作:

Person a = listPeople.getById(1);
Person b = listPeople.getById(2);
bool whosGreater = a > b;

这里有什么我没有看到的吗?在我看来它应该有效。

PS:这是一个家庭作业,所以我真的可以通过声明变量并为它们分配函数返回的内容并摆脱它,但我想知道发生了什么,以便我可以学习。我试过用谷歌搜索它,但我想不出正确的问题。

最佳答案

函数的返回值是一个临时值,而不是“正常”的 Person 对象。临时值只能作为 const 参数引用传递,因此将参数更改为 const 引用应该效果很好;

bool operator > (const Person & a, const Person & b)
{
   //firstname is a string data type
   return (a.FirstName > b.FirstName);      
}

关于c++ - 与函数一起使用时运算符 > 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17633425/

相关文章:

C++ 给属性赋值

c++ - 如何将类的某些 typedef 传递给模板

C++ 为子类重载运算符 <<

c# - 如何在 C# 中重载 [] 运算符

c++ - Bazel Link .so 库位于一个完全不同的、非常远程的文件夹中

c++ - 在运行时访问 v-table

c++ - LAPACK 无法计算特征向量

C++ 为任意集合重载 ostream <<

c++ - 重载 "operator++"返回一个非常量,clang-tidy 提示

c++ - 如何重载全局新运算符