Redefining the Meaning of Operators (Operator Overloading)


In certain classes it makes sense for the developer to redefine operators like + , - , * , / , ++ , , etc. Take the built-in string class (System.String), for example. It is possible to take two string variables and add them together and put the result in a third string variable ( Figure 6.17 ). In the case of strings, Microsoft has redefined the + operator so that when used, the class simply takes the string to the right of the plus and concatenates it to the string to the left of the plus. You can do the same thing in your classesyou can redefine what it means to add, subtract, multiply, divide, etc. instances of your class. This technique is called method overloading.

Figure 6.17 Although it looks like you can add string variables, the truth is that this is only a compiler trick. The string class has a definition for the + operator that calls the string Concat function.
 string first = "Indiana"; string last = "Jones"; string full =  first + " " + last  ; 

Operators fall into two categories: unary operators and binary operators. Unary operators are operators that can be applied directly without taking into consideration another type. An example of a unary operator is ++ ; a developer writes var++ . (See Table 6.1 for a complete list of unary operators.)

Table 6.1. Unary Operators (Operators that Can Be Applied Directly to the Type)

OPERATOR

COMMON PURPOSE

+

Make type positive (return value of the type)

-

Make type negative

!

Negate value. If value is true applying this operator should return false and vice versa.

~

Return bitwise complement. In a numeric value, this means turn the number to binary (zeros and ones) then take each zero and turn it into a one and take each one and turn it into zero.

  ++  

Increase by one unit.

  --  

Decrease by one unit.

true, false

These operators are not applied to the variable directly, but are used whenever the type is compared to the Boolean values true and false.

A binary operator is one that involves two variables. An example of a binary operator is + , a developer writes var1 + var2. (See Table 6.2 for a list of binary operators.)

Table 6.2. Binary Operators (Operators that Require Two Variables)

OPERATOR

COMMON PURPOSE

+ , - , * , /

Add, Subtract, Multiply and Divide two types.

%

Calculate remainder after dividing the first variable by the second.

&

Computes bitwise intersection. With numbers it means turn both numbers into binary (ones and zeros) then take the intersection of both numbers (two ones equals one, anything else equals zero). For example 3 & 5 = 1 . That is because 3 = 11 and 5 = 101 in binary. The intersection of the two numbers is 001 in binary which is also 1 in decimal.

Computes bitwise union. Same principle as & operator except if at least one of the bits is one then the result is one. If both numbers are zero then the result is zero. Therefore 3 5 = 7 (111 in binary).

^

Computes bitwise-exclusive union. Turn the numbers into binary like & and except when comparing the bits the result is 1 if only one of the bits is one, otherwise it is zero. Therefore 3 ^ 5 = 6 .

  <<  

Shift bits of first variable left by the number of bits in the second variable. This concept is a little complicated and a full discussion is beyond the scope of this book, but basically it means take the first value, turn it into bits, then append zeros to the end based on the number of bits in the second operand.

  >>  

Shift bits of first variable right by the number of bits in the second variable.

== , !=

Test for equality or inequality. If you override the == operator, you must override the != operator as well.

> , < , >= , <=

Test for greater than, less than, greater than or equal to, or less than or equal to.

To overload a unary operator:

  1. In a new line type public followed by a space. (Operator overloading functions must be public.)

  2. Type static followed by a space. (Operator overloading functions must be static.)

  3. Type the name of the data type you want to return according to Table 6.3 , followed by a space.

  4. Type the word operator followed by the symbol for the operator you want to overload.

  5. Add parentheses for parameters. Inside the parentheses add a single parameter of the same type as the class you are adding this function to ( Figure 6.18 ).

    Figure 6.18 When a developer uses the ++ operator on a variable of type rectangle, the result is a new rectangle where the width and height are increased by one.
     class Rectangle {    int x,y,width,height;    public Rectangle(int x2,                    int y2,                    int width2,                    int height2)    {      x=x2;y=y2;      width=width2;height=height2;    }  public static Rectangle operator ++(   Rectangle orig)   {   Rectangle newrect = new Rectangle(   orig.x,orig.y,   orig.width+1,   orig.height+1);   return newrect;   }  } 
Table 6.3. Return Types for Unary Operators (What to Return when Overloading Operators)

OPERATORS

RETURN TYPE

+ , - , ! , ~

Can return any type.

++ , --

Must return its own type. That is, if the operator overload is for a class called Checking, it must return an object of type Checking.

true, false

Must return a bool with the value of true or false.

To overload a binary operator:

  1. In a new line, type public followed by a space.

  2. Type static followed by a space.

  3. Type the name of the data type you want to return (it can be any type).

  4. Type the word operator followed by the symbol for the operator you want to overload.

  5. Add parentheses for parameters. Inside the parentheses add two parameters. One of the parameters must be of the same type as the class you are adding this function to; the other parameter can be of any type ( Figure 6.19 ).

    Figure 6.19 For the rectangle example we are using the starting location of the first rectangle and the width and height of the second rectangle. This makes absolutely no sense, but it illustrates how to override the + operator for a class.
     class Rectangle {    int x,y,width,height;    public Rectangle(int x2,                    int y2,                    int width2,                    int height2)    {       x=x2;y=y2;       width=width2;height=height2;    }  public static Rectangle operator +   (Rectangle one, Rectangle two)   {   //not the most efficient way of   //adding two rectangles   //but you get the idea...   Rectangle newrect = new Rectangle(   one.x, one.y,   two.width, two.height);   return newrect;   }  } 

graphics/tick.gif Tips

  • If you override the meaning of true or false you must override the other. It is an error to override true without overriding false.

  • If you override a binary operator, it is legal to have two different definitions for the same data typeone that lists the class that the operator is in first, followed by another data type, and one that lists the other data type first then the class the operator is in. For example, it is legal to define an operator for Class1 + int and one for int + Class1.

  • If you override the == operator, you must override the != operator as well, and vice versa. If you override < then you must override > as well and vice versa. If you override >= then you must override <= as well and vice versa.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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