【问题标题】:addition of 2x2 matrices with operator overloading使用运算符重载添加 2x2 矩阵
【发布时间】:2011-03-03 17:27:50
【问题描述】:

我有以下代码。 没有运算符 + 部分,代码可以正常工作。 它给了我

错误:'final[i][j] = (((matrix*)this)->matrix::mat[i][j] + matr->matrix::mat 中的 'operator=' 不匹配[i][j])'

和

错误:'std::cout 中的'operator

#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;
}

【问题讨论】:

  • 如果函数是非 void,请记住返回值。 double matrix :: determinant () 方法应该返回一个值。
  • 还请记住,拥有operator+() 并不会自动为您提供operator+=(),这可能会很烦人。

标签: c++ matrix operator-keyword


【解决方案1】:

这是因为matrix final[2][2]; 声明了一个二维矩阵数组,所以final[i][j] 是matrix &amp; 类型,并且没有定义相关的运算符。你一定是说double final[2][2];

【讨论】:

    【解决方案2】:

    你需要写operator+为,

    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;
    }
    

    使用final.mat 访问实际的数据成员。同样matrix final[2][2] 声明了matrix 类型的二维数组。它没有做你想做的事!

    【讨论】:

    • 实际上,写operator+= 并以此定义operator+ 可能是要走的路。
    • 你好,它不是那样工作的。我必须做“双最终[2][2]”而不是矩阵最终;
    【解决方案3】:

    您需要为您的矩阵定义一个

    'final' 被定义为一个 2x2 数组 f 'matrix' (matrix final[2][2];)

    因此cout &lt;&lt; final[i][j]; 引用了一个矩阵对象。

    【讨论】:

      猜你喜欢
      • 2012-07-02
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2012-05-04
      相关资源
      最近更新 更多