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