Ad Code

Responsive Advertisement

Operator Overloading

Operator Overloading

This is same as method overloading, where in method overloading we define multiple behaviors to a method but in the case of operator overloading we can define multiple behavior to an Operator.
Eg. -  ‘+’ is overloaded operator which can be used for adding numeric’s and concatenating Strings.
In the some way we can overload any existing operator as per over requirement and use it. To overload an operator we need to define an operator method as following.
[< method >] static <type> operator <opt> (<param def’s >)
{
- stmts
}
- The operator method are always static, return type of an operator method will be the same type of parameters which are passed to the method.
- Add a class Matrix.cs and write the following:
    class Matrix
    {

        // variables for a 2*2 matrix
        int a, b, c, d;
        public Matrix(int a, int b, int c, int d)
        {
            this.a = a; this.b = b;
            this.c = c; this.d = d;
        }
        // overload + operator to add Two matrixes
        public static Matrix operator +( Matrix obj1, Matrix obj2)
    {
        Matrix m = new Matrix(obj1.a + obj2.a, obj1.b + obj2.b, obj1.c + obj2.c, obj1.d + obj2.d);
        return m;
       
    }
       // overload - operator to add Two matrixes
        public static Matrix operator - (Matrix obj1, Matrix obj2)
        {
            Matrix m = new Matrix(obj1.a - obj2.a, obj1.b - obj2.b, obj1.c - obj2.c, obj1.d - obj2.d);
            return m;

        }
        // overloading ToString () method of object class to print value of matrix.
        public override string ToString()
        {
            string str = string.Format("[a:{0},b:{1},c:{2},d:{3}]",a,b,c,d);
            return str;
        }
   
    }

- Add a class TestMatrix.cs and write the following:
    class TestMatrix
    {
        static void Main()
        {
            Matrix m1 = new Matrix(5, 6, 7, 8);
            Matrix m2 = new Matrix(1, 2, 3, 4);

            Matrix m3 = m1 + m2;
            Matrix m4 = m1 - m2;
            Console.WriteLine(m1);
            Console.WriteLine(m2);
            Console.WriteLine(m3);
            Console.WriteLine(m4);
            Console.ReadLine();
        }
}
Reactions

Post a Comment

0 Comments