Overloading comparison operators

I want to overload some comparison operators (<,<=, ==, etc.) and the way I thought of doing it was something as simple as:

1
2
3
4
5
6
7
8
bool Patient::operator<(const Patient & rhs) const{
	if(this.getPriority() < rhs.getPriority()){
		return true;
	}
	else{
		return false;
	}
}


where getPriority() returns a private data member of type int. But when I do this, I get a compiler error with this:

error C2228: left of '.getPriority' must have class/struct/union

Is this not how I would compare two objects of type Patient? Am I using this incorrectly by assuming it refers to the left hand side item of the comparison operator?
When you use 'this' you are working with a pointer, so you must use ' -> ' instead of ' . '
Thanks
I thought of doing it was something as simple as:

It's even easier!

The operator< you're defining has a return type of bool, so it follows that this.getPriority() < rhs.getPriority() evaluates to true or false. Hence the if test is redundant and the function is equivalent to:

1
2
3
bool Patient::operator<(const Patient & rhs) const{
	return (this->getPriority() < rhs.getPriority());{
}


Personally, I would omit the this-> in this case as it's already pretty clear what's going on. But then I'm lazy!
@andywestken Ups, little mistake:
1
2
3
bool Patient::operator<(const Patient & rhs) const{
	return (this->getPriority() < rhs.getPriority());{ // a "{" too much
}

Not a big one.
@hopesfall What andywestken meant is:
You can also use
1
2
3
bool Patient::operator<(const Patient & rhs) const{
	return (getPriority() /* It also means this->getPriority(), just shorter */ < rhs.getPriority());
}
Last edited on
closed account (1yR4jE8b)
Once you've defined the operator <() and operator ==(), you can implement all of the other relational operators simply from #include <utility> and using the rel_ops namespace.

(Warning: this will also automatically give you the relational operators for all other objects with operator< and operator==, just keep in mind that non-template functions take precedence over template functions.

http://www.cplusplus.com/reference/std/utility/rel_ops/

for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <utility>

class Patient {
  //implementation
};

bool operator <(const Patient& lhs, const Patient& rhs) {
  //implementation
}

bool operator ==(const Patient& lhs, const Patient& rhs) {
  //implementation
}

using namespace rel_ops;
//now we also have!
// operator <=, !=, >, >=
Topic archived. No new replies allowed.