No match for operator> when used with function

I overloaded the following more than the statement:

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

Which works fine if I have something like the following:

 Person a = myPersonA; Person b = myPersonB; return myPersonA > myPersonB; 

However, in the Person class, I defined the Person getByID(int id) function Person getByID(int id) , which returns an instance of Person, given this identifier. If I try to use my operator with return values ​​from this function, for example:

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

I get "Error: no match for operator >(Person&, Person&)"

but if I do the following, then it works fine:

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

Is there something I don't see here? I think it should work.

PS: This is for homework, so I could leave with the declaration of variables and assign them what functions return and leave from it, but I would like to know what happens so that I can learn. I tried to take a walk, but I can’t come up with the right question.

+4
source share
2 answers

The return value of the function is a temporary value, not a "normal" Person object. Temporary values ​​can only be passed as references to constant parameters, so changing your parameters to const should work fine,

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

Do it:

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

Regular links cannot bind to temporary objects (like returned getById ()). And you don't mutate in objects, so create const links.

+5
source

Source: https://habr.com/ru/post/1491281/


All Articles