Tuesday, March 23, 2010

User – defined Operators

By using overloading, we can invent new roles for some operators. The need for this feature arises when we deal with objects. In some cases, we might want to test the equality between two objects using the equality operator(==). In this case, we redefine the equality operator in our program to make it work with objects.
Operator overloading is accomplished by using the keyword operator, as shown in the following example:
public static Point operator+ (Point p1, Point p2)
{
    //Implementation of the + operator:
}
This example overloads the + operator in order to use it in adding two objects of the type Point.
Adding two points means adding the x and y coordinates of each point. If the coordinates of the first point are (x1,y1) and the coordinates of the second point are (x2,y2), the result is a new point at the location (x1+x2, y1+y2). These details should be included in the implementation of overloading the operator+.
Notice in the syntax that the redefined + operator follows the keyword operator. Other examples are:
operator+
operator-
operator==
The method used for operator overloading is always static.
 The operators that are classified as binary operator on two operands, such as + and *. The operators that are classified as unary operate on one operand, such as ++ and --.
The following example overloads the + operator to add two points, p1 and p2, and displays the coordinates of the resulting point.
//Example 6-9.cs
//Overloading operators
using System;
public class Point
{
    public int x;
    public int y;
    //Constructor:
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    //Overloading the + operator:
    public static Point operator+ (Point p1, Point p2)
    {
        //Return the sum as a point:
        return new Point(p1.x + p2.x, p1.y + p2.y);
    }
    static void Main()
    {
        Point p1 = new Point(15,33);
        Point p2 = new Point(10,12);
        //Add the two Point objects using the overloading + operator:
        Point sum = p1 + p2;
        //Display the objects:
        Console.WriteLine(“Point #1: ({0}, {1})”, p1.x, p1.y);
        Console.WriteLine(“Point#2: ({0},{1})”.p2.x,p2.y);
        Console.WriteLine(“Sum of the two points: ({0}, {1})”, sum.x, sum.y);
    }

}

No comments:

Post a Comment