Write a C++ program to illustrate the operator overloading concept using Matrix addition as an example.

Program Algorithm:
Step 1: Create a class ’matrix’ with the constructor that sets the value of its member variables.
Step 2: This class also overloads the + and = operator with proper operator overloaded functions.
Step 3: Define the operators.
Step 4: Create the object of this class and call these overloaded functions.

Program Code:
#include<iostream.h>
class Matrix
{
public:
float row,col;
float **arr;
Matrix();
Matrix(float,float);
int inputDim(float,float);
int getMatrix();
Matrix operator+(Matrix);
Matrix operator=(Matrix&);
};
int Matrix::getMatrix()
{
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
cin>>arr[i][j];
return 0;
}
Matrix::Matrix(float r,float c)
{
row=r;
col=c;
arr=new float*[row];
for(int i=0;i<row;i++)
arr[i]=new float[col];
}
Matrix::Matrix()
{
row=col=0;
arr=NULL;
}
int Matrix::inputDim(float r,float c)
{
row=r;
col=c;
arr=new float*[row];
for(int i=0;i<row;i++)
arr[i]=new float[col];
return 0;
}
Matrix Matrix::operator+(Matrix m)
{
Matrix t;
t.inputDim(m.row,m.col);
for(int i=0;i<m.row;i++)
for(int j=0;j<m.col;j++)
t.arr[i][j]=arr[i][j]+m.arr[i][j];
return t;
}
Matrix Matrix::operator=(Matrix &m)
{
for(int i=0;i<m.row;i++)
for(int j=0;j<m.col;j++)
arr[i][j]=m.arr[i][j];
return *this;
}
int main()
{
int r,c;
int getDimension(int &r,int &c);
int showResult(Matrix);
cout<<"\nEnter the matrix size of A\n";
getDimension(r,c);
Matrix a(r,c);
cout<<"\nEnter the matrix A\n";
a.getMatrix();
cout<<"\nEnter the matrix size of B\n";
getDimension(r,c);
Matrix b(r,c);
cout<<"\nEnter the matrix B\n";
b.getMatrix();
if(a.row==b.row && a.col==b.col)
{
Matrix x(r,c);
x=a+b;
cout<<"\nMatrix A:\n";
showResult(a);
cout<<"\nMatrix B:\n";
showResult(b);
cout<<"\nResultant Matrix:\n";
showResult(x);
}
else
cout<<"\nAddition not possible\n";
return 0;
}
int getDimension(int &r,int &c)
{
cout<<"\nEnter row and column:\n";
cin>>r>>c;
return 0;
}
int showResult(Matrix x)
{
for(int i=0;i<x.row;i++)
{
for(int j=0;j<x.col;j++)
cout<<x.arr[i][j]<<" ";
cout<<"\n";
}
return 0;
}

Output:
Enter the matrix size of A:
Enter rows & columns 2 2
Enter the matrix A:
1 1 1 1
Enter the matrix size of B:
Enter rows & columns 2 2
Enter the matrix B:
1 1 1 1
Matrix A: 1 1 1 1
Matrix B: 1 1 1 1
Resultant Matrix:
2 2
2 2
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: