Overloading the Relational Operators


The relational operators, such as = = or <, can also be overloaded and the process is straightforward. Usually, an overloaded relational operator returns a true or false value. This is in keeping with the normal usage of these operators and allows the overloaded relational operators to be used in conditional expressions. If you return a different type result, then you are greatly restricting the operator’s utility.

Here is a version of the ThreeD class that overloads the < and > operators. In the implementation shown here, one ThreeD object is less than another only if all three of its coordinates are less than the corresponding coordinates in the other object. Similarly, one ThreeD object is greater than another only if all three of its coordinates are greater than the corresponding coordinates in the other object. Of course, more subtle determinations are possible.

 // Overload < and >. using System; // A three-dimensional coordinate class. class ThreeD {   int x, y, z; // 3-D coordinates   public ThreeD() { x = y = z = 0; }   public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }   // Overload <.   public static bool operator <(ThreeD op1, ThreeD op2)   {     if((op1.x < op2.x) && (op1.y < op2.y) && (op1.z < op2.z))       return true;     else       return false;   }   // Overload >.   public static bool operator >(ThreeD op1, ThreeD op2)   {     if((op1.x > op2.x) && (op1.y > op2.y) && (op1.z > op2.z))       return true;     else       return false;   }   // Show X, Y, Z coordinates.   public void show()   {     Console.WriteLine(x + ", " + y + ", " + z);   } } class ThreeDDemo {   public static void Main() {     ThreeD a = new ThreeD(5, 6, 7);     ThreeD b = new ThreeD(10, 10, 10);     ThreeD c = new ThreeD(1, 2, 3);     Console.Write("Here is a: ");     a.show();     Console.Write("Here is b: ");     b.show();     Console.Write("Here is c: ");     c.show();     Console.WriteLine();     if(a > c) Console.WriteLine("a > c is true");     if(a < c) Console.WriteLine("a < c is true");     if(a > b) Console.WriteLine("a > b is true");     if(a < b) Console.WriteLine("a < b is true");   } }

The output from this program is shown here:

 Here is a: 5, 6, 7 Here is b: 10, 10, 10 Here is c: 1, 2, 3 a > c is true a < b is true

An important restriction applies to overloading the relational operators: You must overload them in pairs. For example, if you overload <, you must also overload >, and vice versa. The operator pairs are

= =

!=

<

>

<=

>=

One other point: If you overload the = = and != operators, then you will usually need to override Object.Equals( ) and Object.GetHashCode( ). These methods and the technique of overriding are discussed in Chapter 11.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net