Thursday, July 1, 2010

Binary operators overloading

Binary operators overloading there are two arguments
the general form of operator function for binary operators is as follows.
One of the parameters has to be of a type in which the operator is declared. They include +, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >=, and <=.
public static return_type operator op (Type1 t1, Type2 t2)
{
//Statements
}

Example

public static biop operator +(biop ob1,biop ob2)
{
biop b=new biop();
b.real=ob1.real+ob2.real;
b.im=ob1.im+ob2.im;
return b;
}


Example program in C# Console application

using System;
class biop
{
public int real,im;
public biop(){}
public biop(int r,int i)
{
real=r;
im=i;
}
public void disp(){Console.WriteLine(real+"+i"+im);}
public static biop operator +(biop ob1,biop ob2)
{
biop b=new biop();
b.real=ob1.real+ob2.real;
b.im=ob1.im+ob2.im;
return b;
}
}
class binaryoperator
{
public static void Main(string[] args)
{
biop b1=new biop(5,5);
b1.disp();
biop b2=new biop(2,2);
b2.disp();
biop b3=b1+b2;
b3.disp();
}
}

No comments:

Post a Comment