Operator Overloading provide facility to give user define meaning to operator. With the help of operator overloading one can perform operation on non-standard data type(user defined data type). For example an '+' operator can add only predefine data type i.e int,long,float,double. Suppose we want to add two user defined data type say two matrix then the '+' operator is overloaded to perform addition of two matrix. The following program illustrate the operator overloading concept.
/*Addition of two matrix*/
#include<iostream.h>
#include<conio.h>
struct matrix //user defined data type
{
int arr[3][3];
};
matrix operator + (matrix a,matrix b); //method declaration
matrix operator - (matrix a,matrix b);
void display(matrix);
void main()
{
matrix x={
2,3,4,
7,3,9,
6,8,4
};
matrix y={
9,6,1,
8,3,4,
3,8,8
};
matrix p,q;
clrscr();
p=x+y;
q=y-x;
display(p);
display(q);
getch();
}
//operator '+' is overloaded to add two matrix.
//operator '+' is overloaded to add two matrix.
matrix operator + (matrix a,matrix b)
{
int i,j;
matrix c;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c.arr[i][j]=a.arr[i][j]+b.arr[i][j];
}
}
return c;
}
//operator '-' is overloaded to subtract two matrix
//operator '-' is overloaded to subtract two matrix
matrix operator - (matrix a,matrix b)
{
int i,j;
matrix c;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c.arr[i][j]=a.arr[i][j]-b.arr[i][j];
}
}
return c;
}
void display(matrix s)
{
int i,j;
cout<<"\n"<<"\n";
for(i=0;i<3;i++)
{
cout<<"\n";
for(j=0;j<3;j++)
{
cout<<"\t"<<s.arr[i][j];
}
}
}
No comments:
Post a Comment