开发者

addition of 2x2 matrices with operator overloading

开发者 https://www.devze.com 2023-02-14 11:25 出处:网络
I have the following code. The code works fine without the operator + part. It gives me error: no match for ‘operator=’ in ‘final[i][j] = (((matrix*)this)->matrix::mat[i][j] + matr->matrix::mat[

I have the following code. The code works fine without the operator + part. It gives me

error: no match for ‘operator=’ in ‘final[i][j] = (((matrix*)this)->matrix::mat[i][j] + matr->matrix::mat[i][j])’

and

error: no match for ‘operator<<’ in ‘std::cout << final[i][j]

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>

using namespace std;


class matrix {

private :

int i,j;
double mat[2][2];


public :
matrix () {
}

void getdata();
double determinant();
matrix operator + (matrix &);

};

//getdata
void matrix :: getdata() {
cout <<"Please provide a 2x2 matrix :"<<endl;

    for (int i=0;i<2;i++) {
        for (int j=0;j<2;j++) {
cout <<"Give the elements of the matrix : "<<endl;
cin >> mat开发者_开发问答[i][j];
        }
        }
}

//compute determinant
double matrix :: determinant () {

double det;

det = mat[0][0]*mat[1][1] -mat[0][1]*mat[1][0];


cout <<"The determinant of the matrix is :"<<det<<endl;


}

//compute addition
matrix matrix ::operator +(matrix &matr) {
matrix final[2][2];
for (int i=0;i<2;i++) {
    for (int j=0;j<2;j++) {
final[i][j]=mat[i][j]+matr.mat[i][j];
    }
}
cout <<"The addition of the two matrices is :"<<endl;

for (int i=0;i<2;i++) {
    for (int j=0;j<2;j++){
cout << final[i][j];
    }
cout <<endl;
}

}


int  main()
{
   matrix pinakas1,pinakas2;
   pinakas1.getdata();
   pinakas2.getdata();
   pinakas1.determinant();
   pinakas2.determinant();
   pinakas1+pinakas2;


    return 0;
}


That's because matrix final[2][2]; declares a 2-d array of matrices, so final[i][j] is of type matrix & and the relevant operators aren't defined. You must have meant double final[2][2];


You need to write operator+ as,

matrix matrix ::operator +(const matrix &matr) 
{
    matrix final;
    for (int i=0;i<2;i++) 
    {
        for (int j=0;j<2;j++) 
        {
            final.mat[i][j]=mat[i][j]+matr.mat[i][j];
        }
    }
    return final;
}

Use final.mat to access the actual data member. Also matrix final[2][2] declares two dimensional array of type matrix. It doesn't do what you intend it to do!


You need to define a << operator for your matrix.

'final' is defined as a 2x2 array f 'matrix' (matrix final[2][2];)

Therefore cout << final[i][j]; references a matrix object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号