Han*_*año 4 c++ operator-overloading
我重载了以下大于运算符:
bool operator > (Person & a, Person & b)
{
//firstname is a string data type
return (a.FirstName > b.FirstName);
}
Run Code Online (Sandbox Code Playgroud)
如果我有以下内容,哪个工作正常:
Person a = myPersonA;
Person b = myPersonB;
return myPersonA > myPersonB;
Run Code Online (Sandbox Code Playgroud)
但是,在我的Person类中,我已经定义了一个Person getByID(int id)函数,该函数通过给定的ID返回Person的实例.如果我尝试使用我的运算符与此函数返回的值,如下所示:
bool whosGreater = listPeople.getById(1) > listPeople.getById(2);
Run Code Online (Sandbox Code Playgroud)
我明白了 "Error: no match for operator >(Person&, Person&)"
但如果我做以下工作就可以了:
Person a = listPeople.getById(1);
Person b = listPeople.getById(2);
bool whosGreater = a > b;
Run Code Online (Sandbox Code Playgroud)
有没有我在这里看到的东西?在我看来它应该工作.
PS:这是一个家庭作业,所以我可以真正逃脱声明变量并为它们分配函数返回和逃避它,但我想知道发生了什么,以便我可以学习.我试过谷歌搜索它,但我无法提出正确的问题.
函数返回的值是临时值,而不是"普通"Person对象.临时值只能作为const参数引用传递,因此将参数更改为const引用应该可以正常工作;
bool operator > (const Person & a, const Person & b)
{
//firstname is a string data type
return (a.FirstName > b.FirstName);
}
Run Code Online (Sandbox Code Playgroud)
做了:
bool operator > (Person const & a, Person const & b)
{
//firstname is a string data type
return (a.FirstName > b.FirstName);
}
Run Code Online (Sandbox Code Playgroud)
普通引用不能绑定到临时对象(如getById()返回的对象).并且你没有变异传入对象,所以使引用const.
| 归档时间: |
|
| 查看次数: |
286 次 |
| 最近记录: |