我想写一个cpp程序来做与运算符重载的矩阵运算。使用赋值运算符导致编译器错误
我的类矩阵具有以下变量:
int m,n // order of the matrix
int **M;
起初,我有一个构造函数和析构函数使用new和delete操作符来分配和**中号释放内存。我也有过载+, - 和*运算符的函数。但是当我运行程序时,我得到了垃圾值作为结果。此外,在运行时,我得到一个错误(检测到glibc)。
在这里的类似问题告诉我,我应该添加一个“深拷贝”二维数组的复制构造函数。我也是这样做的。但同样的问题依然存在。
所以我给overload =运算符添加了一个函数。现在,无论何时使用'='运算符,我都会收到编译时错误(对于调用'Matrix :: Matrix(Matrix)'的匹配函数。
这里是我的功能:
拷贝构造函数
Matrix(Matrix& other) {
m=other.m;
n=other.n;
M= new int *[m];
for(int i=0;i<m;i++)
M[i] = new int[n];
//deep copying matrix
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
M[i][j]=other.M[i][j];
}
超载*:
Matrix Matrix::operator*(Matrix A) {
Matrix pro(m,A.n);
for(int i=0;i<m;i++)
for(int j=0;j<A.n;j++) {
pro.M[i][j]=0;
for(int k=0;k<n;k++)
pro.M[i][j]+=(M[i][k]*A.M[k][j]);
}
return pro;
}
超载=::
Matrix Matrix::operator=(Matrix a) {
m=a.m;
n=a.n;
/*
M=new int* [m];
for(int i=0;i<m;i++) //I also tried allocating memory in this function
M[i]=new int[n];
*/
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
M[i][j]=a.M[i][j];
return *this;
}
在main()
Matrix M1(m,n);
Matrix M2(p,q);
//inputting both matrices
Matrix M3(m,n);
Matrix M4(m,q);
M3 = M1 + M2; // Compile Time Error here...
M3.show();
M3 = M1 - M2; //...here...
M3.show();
M4 = M1*M2; //...and here.
M4.show();
编译时错误:调用的Matrix矩阵::(矩阵)“
'矩阵(矩阵&)'我强烈怀疑你想要那样。也许用'const'? –
您还应该使用'const&'作为其他函数中的参数,以避免不断复制矩阵。 –
'Matrix Matrix :: operator =(Matrix a)... return * this;'没有错?它需要一个Matrix(Matrix)构造函数 – user3125280