Thursday, October 25, 2012

.NET LAB OPERATOR OVERLOADING PROGRAMS


Operator overloading
Aim  
To write a program to implement binary operator overloading and Unary operator overloading.
The mechanism of assigning a special meaning to an existing  operator  is called operator Overloading
Unary operator overloading
To overload the unary operators such as unary plus unary minus , ++, -- etc is called unary operator overloading
Binary operator overloading
To overload the binary operators such as +,-,*, / etc, is called binary operator overloading.
Algorithm
1. Start the process
2. Create a class and initialize values for the class members by using the constructor method
3. Define  a method  to  overload the  given operator
4. Instantiate an object for the class and invoke the method for overloading
5. Display the values by invoking the display method
6. Terminate the process




Program
Unary Operator Overloading
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Unaryop
{
    class Unary
    {

        private int n1;
        private int n2;
        private int n3;
        public Unary(int a, int b, int c)
        {
            n1 = a;
            n2 = b;
            n3 = c;
        }
        public void display()
        {
           Console.WriteLine("n1 ={0}}", n1);
Console.WriteLine("n2 ={0}}", n2);
Console.WriteLine("n3 ={0}}", n3);
                  }

        public Unary()
        { }
        public static Unary operator -(Unary opr)
        {
            Unary obj = new Unary();
            obj.n1 = -opr.n1;
            obj.n2 = -opr.n2;
            obj.n3 = -opr.n3;
            return obj;
        }
    }
    class Uop
    {
        public static void Main(string[] args)
        {
            Unary op = new Unary(1, 5, 6);
            Unary op1 = new Unary();
            Console.WriteLine("Unaryoperator Overloading");
            Console.WriteLine("*************************");
            Console.WriteLine("\nBefore Overloading");
            Console.WriteLine("------------------");
            op.display();
            op1 = -op;
            Console.WriteLine("\nAfter overloading");
            Console.WriteLine("-----------------");
            op1.display();
            Console.ReadLine();
       }
    }
}
Output
Unaryoperator Overloading
*******************************
Before Overloading
n1=1
n2=5
n3=6
After overloading
n1=-1
n2=-5
n3=-6

No comments:

Post a Comment