【问题标题】:Compilation error : No match for overloaded operator编译错误:重载运算符不匹配
【发布时间】:2013-03-17 09:31:02
【问题描述】:

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

gcc 错误: “'z = Matrix::operator+(Matrix&)((* & y))'中的'operator='不匹配' 候选人是: 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;
}   

};

【问题讨论】:

  • 请在您的问题中包含 completeunedited 错误消息,并指出它们是关于哪些行。
  • 请出示您的class Matrix声明的相关部分。另外,编译错误不在GCC内部,而是在你的代码内部,所以我觉得标题容易出错......
  • 确实有一个很容易看到的问题,那就是如果if 语句为假,则operator+ 函数不会返回任何内容。这可能会导致问题和未定义的行为。
  • 要重载 += 运算符正确地使参数 const 引用,例如像这样Matrix operator+ (const Matrix&amp; M){
  • 谢谢大家! :) 我明白 :)

标签: c++ gcc compiler-errors


【解决方案1】:
Matrix operator+ (Matrix &M){
Matrix& operator= (Matrix &M){

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

【讨论】:

    猜你喜欢
    • 2013-08-28
    • 2018-07-19
    • 2017-08-10
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多