编译错误:无法匹配重载运算符

时间:2013-03-17 09:31:02

标签: c++ gcc compiler-errors

这是我的代码的一部分,当我编译它时,它说 1:不匹配operator = 2:参数1从'Matrix'到'Matrix&'没有已知的转换 但如果我删除运算符+部分它的工作原理 问题出在哪儿?! :|

gcc错误: “在'z = Matrix :: operator +(Matrix&)('*& y))'''''''''''''''''''''''''''''' 候选人是: ATRIX和放大器;矩阵算子:: =(矩阵&安培)  参数1从“Matrix”到“Matrix&”没有已知的转换“

class Matrix {
  //friend list:
  friend istream& operator>>(istream& in, Matrix& m);
  friend ostream& operator<<(ostream& in, Matrix& m);

  int** a;    //2D array pointer
  int R, C;   //num of rows and columns
  static int s1, s2, s3, s4, s5;
 public:
  Matrix();
  Matrix(const Matrix&);
  ~Matrix();
  static void log();

  Matrix operator+ (Matrix &M){
    if( R == M.R && C == M.C ){
        s4++;
        Matrix temp;
        temp.R = R;
        temp.C = C;         temp.a = new int*[R];
        for(int i=0; i<R; i++)
            temp.a[i] = new int[C];

        for(int i=0; i<R; i++)
            for(int j=0; j<C; j++)
                temp.a[i][j] = a[i][j] + M.a[i][j];

        return temp;
    }   
}

  Matrix& operator = (Matrix& M){
s5++;
if(a != NULL)
{
    for(int i=0; i<R; i++)
        delete [] a[i];
    delete a;
    a = NULL;
    R = 0;
    C = 0;
}
R = M.R;
C = M.C;
a = new int*[R];
for(int i=0; i<R; i++)
    a[i] = new int[C];

for(int i=0; i<R; i++)
    for(int j=0; j<C; j++)
        a[i][j] = M.a[i][j];    

return *this;
}   

};

1 个答案:

答案 0 :(得分:2)

Matrix operator+ (Matrix &M){
Matrix& operator= (Matrix &M){

他们都有同样的问题 - 参数类型应该是const Matrix&(就像在复制构造函数中一样)。否则,您无法将临时对象传递给运算符。