Thursday, July 9, 2009

How to overload C++ relational operator?

The program i'm trying to write is a simple game of war with 52 cards, and say two cards on the board is KC and 10D (King of clubs and 10 of diamond), or any other cards. How would I overload the %26gt; %26lt; = operators to have KC win?





Thanks alot!

How to overload C++ relational operator?
Well it is hard to tell you exactly what's inside the function because only you know what %26gt; is suppose to mean for your class. Let's assume that suit is meaningless and only the value of the card is important and that you have some numerical value scheme for picture cards, ace, etc. Then you would have something like:





bool operator %26gt;( MyClass %26amp;rhs)


{


return(rhs.cardvalue %26lt; value);


}





or if you use the other form





bool operator %26gt; (const MyClass %26amp;lhs, const MyClass %26amp;rhs)


{


(return rhs.cardvalue %26lt; lhs.cardvalue);


}





but remember to make it a friend of MyClass.
Reply:bool operator %26gt;( MyClass %26amp; t);


No comments:

Post a Comment