22.2 Operator overloading proper


After seeing an example, you should have a good idea of what operator overloading is all about. Now, let's go into the specifics. The operator [2] method has to be defined like this:

[2] operator is a C# keyword.

 public static <return_value> operator <operator to overload> (<operand1>, [<operand2>]); 

The following lists some rules that need to be followed when overloading an operator.

  1. You cannot overload just any C# operator, and you cannot define your own operator. Only the operators shown in Table 22.1 can be overloaded.

    Table 22.1. Operators that can be overloaded in C#

    Category

    Operators

    Unary operators

    + “ ! ~ ++ -- true false

    Binary operators

    + “ * / % and ^ << >>

    Comparison operators

    == != < > <= >=

  2. The +=, - =, / =, * =, % =, & =, ^ =, =, >> =, and << = assignment operators are automatically overloaded when the corresponding +, - , / , * , % , & , ^ , , >> , and << operators are overloaded. [3]

    [3] In C++, the = assignment operator can be overloaded. In C#, you cannot overload = but if you overload a binary operator, the corresponding assignment operator is automatically overloaded. See the example which follows .

    For example, if you overload the * operator, * = will be automatically overloaded. And the following statement assigns the result of f3*f1 to f3 :

     f3 *= f1; 
  3. You can pass in only one or two parameters into the operator method, depending on whether you are overloading a unary or binary operator. For example, if you want to overload the unary operator ++, the operator method you need to write can only take in one (and only one) parameter.

  4. The first parameter taken into the operator method must be of the same type as the class in which the method is defined. The second parameter (if present) can be of any type.

  5. Overloaded operators must be public and static.

  6. If you overload true or false , the operator method must return either true or false only. Otherwise, the operator method can return any type, although it commonly returns the class in which it is defined.

Let's examine the operator method's signature in the Fraction example:

 public static Fraction operator * (Fraction f1, Fraction f2) 

Since the binary * operator is being overloaded, the operator method must take in two parameters (in accordance with rule #3 above). The first parameter must be of type Fraction because this method is defined within the Fraction class (in accordance with rule #4 above). It is not mandatory that the method returns a Fraction , nor takes in a Fraction as the second parameter. And, of course, this method is declared with the public and static keywords (rule #5).



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

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