2013-03-17 81 views
1

这里是我的代码的一部分,当我编译它时,它说 1:没有匹配运算符= 2:没有已知的从'Matrix'到'Matrix &“ 但如果我删除操作+部分它的工作原理 哪里出了问题? :|编译错误:重载运算符不匹配

GCC错误: “无匹配关于 '操作符=' 在 'Z =矩阵::运算+(基质&)((* & Y))' 候选是: ATRIX &矩阵::运算=(矩阵&) 没有已知的转换为自变量1从 '矩阵' 到 '矩阵&“'

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

请包括_complete_和你的问题_unedited_错误信息,并指出他们对哪些行。 – 2013-03-17 09:32:35

+0

并请显示您的'类矩阵'声明的相关部分。此外,编译错误是不是里面GCC,它是你的代码里面,所以我觉得标题是容易出错... – 2013-03-17 09:33:27

+1

您_do_有问题,很容易看到,那就是'运营商+'功能呢如果if语句为false,则不返回任何内容。这可能会导致问题和未定义的行为。 – 2013-03-17 09:35:31

回答

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

他们都分享他同样的问题 - 参数类型应该是const Matrix&(就像在拷贝构造函数)。否则,您无法将临时对象传递给操作员。