Why does this method for operator overloading not work here?
Solution 1:
The error message:
no match for 'operator<' (operand types are 'const Person' and 'const Person')
This tells you that the lhs and rhs object of operator are const objects. and the compiler can not find an operator that will work two const Person objects.
If I look at your implementation:
bool operator < (const Person& p1) {
return (this->height > p1.height);
}
I see that the right-hand value p1
can be a const reference. But the left-hand value (the owner of the method) is being treated as non cost. So this implementation does not match the requirements needed.
But we know this operator is not changing the state of the object so we can simply mark this as a const member function.
bool operator < (const Person& p1) const {
// ^^^^^ Add the const here.
return (this->height > p1.height);
}