Reputation: 83
Cannot figure out what's happening. Why is operator overloading not working in this code ?
class matrix
{
protected:
int matrix1[5][5],matrix2[5][5],resultmatrix[5][5];
int m,n,p,q,i,j,k,l;
public: matrix()
{
}
void getdata();
//double determinat;
matrix operator +(matrix);
void showmatrix();
};
void matrix::getdata()
{
cout<<"\n"<<"enter no of rows for matrix1 : "<<"\n";
cin>>m;
cout<<"\n"<<"enter no of columns for matrix1 : "<<"\n";
cin>>n;
cout<<"\n"<<"enter no of rows for matrix2 : "<<"\n";
cin>>p;
cout<<"\n"<<"enter no of columns for matrix2 : "<<"\n";
cin>>q;
if(m==p&&n==q)
{
cout<<"\n"<<"matrixes can be added"<<"\n";
}
else
{
cout<<"\n"<<"matrixes can not be added"<<"\n";
exit(0);
}
cout<<'\n'<<"please provide for matrix1: "<<"\n";
for( i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>matrix1[i][j];
}
}
cout<<'\n'<<"please provide for matrix2: "<<"\n";
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>matrix2[i][j];
}
}
}
matrix matrix::operator+( matrix matrixobj)
{ matrix tempmatrixobj;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
matrixobj.resultmatrix[i][j]=
tempmatrixobj.matrix1[i][j]+tempmatrixobj.matrix2[i][j];
}
}
return matrixobj;
//return tempmatrixobj;
// return *this;
}
void matrix::showmatrix()
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<resultmatrix[i][j]<<"\t";
}
cout<<"\n";
}
}
int main()
{
matrix matrixobj1,matrixobj2;
matrix resultmatrix;
matrixobj1.getdata();
matrixobj2.getdata();
resultmatrix=matrixobj1+matrixobj2;
resultmatrix.showmatrix();
return 0;
}
Addition part of the code not working at all and it takes the values twice for each matrix and thens outputs some memory addresses only.
output:
enter no of rows for matrix1 :
3
enter no of columns for matrix1 :
3
enter no of rows for matrix2 :
3
enter no of columns for matrix2 :
3
matrixes can be added
please provide for matrix1:
1 1 1
1 1 1
1 1 1
please provide for matrix2:
1 1 1
1 1 1
1 1 1
enter no of rows for matrix1 :
2
enter no of columns for matrix1 :
2
enter no of rows for matrix2 :
2
enter no of columns for matrix2 :
2
matrixes can be added
please provide for matrix1:
1 1
1 1
please provide for matrix2:
1 1
1 1
-1717986920 -1717986920
-1717986920 -1717986920
Press any key to continue . . .
Upvotes: 0
Views: 59
Reputation: 92211
The code doing the addition
matrixobj.resultmatrix[i][j]=tempmatrixobj.matrix1[i] [j]+tempmatrixobj.matrix2[i][j];
adds values from the tempmatrixobj
, not from the parameters to the operator+
.
Upvotes: 2