Sample problem

I was given the following sample problem:

1
2
3
4
5
6
class Tower { 
private:
int height; 
public:
Tower(int i) { height = i;}
bool operator<(Tower rhs) { return (height < rhs.height); } }; // end of class 


I need to use this class to create user functions, they cant be member or friends to do the following:

1
2
3
4
5
6
Tower a(5), b(10), c(5); 
if ( a == c) cout << "Tower a has same height as c"; 
if(b>a) cout<<"Towerbisbiggerthana"; 
if ( b >= a) cout << "Tower b is at least as big as a"; 
if ( c <= b) cout << "Tower c is no bigger than a";
if ( a != b) cout << "The height of Tower a is not same as that of b";


I've been racking my brain for 2 days on this, and am at my wits end. Does anyone have any suggestions?
Last edited on
so you need to express equality with less. if a==b, then is a<b? no. is b<a? no. is there any pair of values a,b so that a is not <b and b is not <a but a is not == b? no. so a==b is true when both a<b and b<a are false. is it clear?
All of those operations (==, >, >=, <=, !=) can be replaced with the operator < (with a little more code of course).

For example, to find (a == c), you can check if a is less than c, and then check if a is greater than c (in other words, if c is less than a because you only have the less than operator to use). If neither are less than the other, then they must be equal.

The rest of the operations follow the same logic.
1
2
3
4
5
6
7
8
9
bool operator==(const Tower& tower, const& Tower rhs) { return !(tower<rhs || rhs<tower) ; }

bool operator>(const Tower& tower, const& Tower rhs) { return (rhs<tower ) ; }

bool operator>=(const Tower& tower, const& Tower rhs) { return !(tower<rhs) ; }

bool operator<=(const Tower& tower, const& Tower rhs) { return !(rhs<tower); }

bool operator!=(const Tower& tower, const& Tower rhs) { return !(tower==rhs) ; }


Would this be correct?
Last edited on
2nd and 3rd aren't. If a is not lower than b, that it is either greater or equal.
Last edited on
Hmm, was that reply before I made my edits? I hastily put up my work, then saw some errors. Above is the final code.

Thanks for all the quick replies.
Anyone had a chance to look and see if these are correct?
Test them to know for sure.
But yes, they do look correct - except for this:
1
2
3
bool operator==(const Tower& tower, const& Tower rhs) { ... }
//                                  ^^^^^^^^^^^^^^^^
//                       should be: const Tower& rhs) { ... } 
Last edited on
However bool Tower::operator<(Tower rhs) should be bool Tower::operator<(const Tower &rhs) const in order to use it with constants objects
Topic archived. No new replies allowed.