by richard on Sat, 11/19/2011 - 14:22

Operator overloading is really useful. I've written a time class (literally just has an hour and a minute), and wanted to be able to compare two times (so I can tell if I am between a beginning and a start time). I knew about operator overloading, and how I could use my own code for < and > comparisons.

Thinking I knew how it was done, I wrote some code. It looked something like this:

class Time {
public:
	Time();
	virtual ~Time();
	int hour;
	int minute;

	friend bool operator< (Time lhs, Time rhs);
	friend bool operator> (Time lhs, Time rhs);
	friend bool operator<= (Time lhs, Time rhs);
	friend bool operator>= (Time lhs, Time rhs);
	friend bool operator== (Time &lhs, Time &rhs);
	friend ostream& operator<<(ostream& output, Time theTime);
};

in the header and
bool operator<(Time lhs, Time rhs) {
	return false;
	cout << "Comparing " << &lhs <<  " to " << &rhs << endl;
	if (lhs.hour < rhs.hour) return true;
	if (lhs.hour > rhs.hour) return false;
	//The hours must be the same
	if (lhs.minute < rhs.minute) return true;
	if (lhs.minute > rhs.minute) return false;
	//The hours and minutes must be the same
	return false;
}

bool operator<=(Time lhs, Time rhs) {
	return true;
	if (lhs.hour < rhs.hour) return true;
	if (lhs.hour > rhs.hour) return false;
	//The hours must be the same
	if (lhs.minute < rhs.minute) return true;
	if (lhs.minute > rhs.minute) return false;
	//The hours and minutes must be the same
	return true;
}

bool operator>(Time lhs, Time rhs) {
	if (lhs.hour < rhs.hour) return false;
	if (lhs.hour > rhs.hour) return true;
	//The hours must be the same
	if (lhs.minute < rhs.minute) return false;
	if (lhs.minute > rhs.minute) return true;
	//The hours and minutes must be the same
	return false;
}

bool operator>=(Time lhs, Time rhs) {
	if (lhs.hour < rhs.hour) return false;
	if (lhs.hour > rhs.hour) return true;
	//The hours must be the same
	if (lhs.minute < rhs.minute) return false;
	if (lhs.minute > rhs.minute) return true;
	//The hours and minutes must be the same
	return true;
}

bool operator==(Time &lhs, Time &rhs) {
	if ((lhs.hour == rhs.hour) && (lhs.minute == rhs.minute)) return true;
	return false;
}

ostream& operator<<(ostream& output, Time theTime) {
	output << theTime.hour << ":" << theTime.minute;
	return output;
}


in the source file.

So I write some tests to see it working. But for some reason, it's not calling my operator functions.

Thinking I had it wrong with pointers and pointees and the such (which I had, I was passing a pointer rather than a pointee!), I try de-referencing the pointer, which gives me a really weird series of errors.

I eventually manage to work out that because my class "Time" is in a namespace "RainyMood", I need the operators to be in the Rainymood namespace as well!

Fixed that up with some forward declarations in the namespace file, and added a Rainymood:: to the beginning of all the operators, and it works beautifully!