【发布时间】:2014-02-08 12:43:27
【问题描述】:
我正在尝试编写一个 cpp 程序来使用运算符重载进行矩阵运算。
我的班级矩阵有以下变量:
int m,n // order of the matrix
int **M;
起初,我有一个构造函数和一个析构函数,使用 new 和 delete 运算符为 **M 分配和释放内存。我还有重载 +、- 和 * 运算符的函数。但是当我运行程序时,我得到了垃圾值作为结果。此外,在运行时,我收到一个错误(检测到 glibc)。
这里的类似问题告诉我,我应该添加一个“深度复制”二维数组的复制构造函数。我也这样做了。但同样的问题仍然存在。
所以我向重载 = 运算符添加了一个函数。现在,每当我使用“=”运算符时,都会出现编译时错误(没有匹配的函数调用“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::Matrix(Matrix)'
【问题讨论】:
-
Matrix(Matrix&)我强烈怀疑你想要那个。也许是const? -
其他函数的参数也应该使用
const&,以避免不断复制矩阵。 -
Matrix Matrix::operator=(Matrix a)... return *this;是不是错了?它需要一个 Matrix(Matrix) 构造函数 -
如果本练习的目的是学习如何正确编写矩阵类和重载运算符,只需抛弃手动内存管理并使用
std::vector<std::vector<int>>即可。另一方面,如果练习的目的是学习如何在 C++ 中管理资源,请阅读三法则(C++ 11 中的五法则)、RAII,最后阅读零法则(在那请订购)。 -
对于运算符重载,wiki 有一个关于该主题的非常好的线程。此外,三/五规则是许多问题都涉及的主题,因此这绝对是重复的。
标签: c++ matrix operator-overloading dynamic-allocation