gpt4 book ai didi

c++ - 使用赋值运算符导致编译器错误

转载 作者:行者123 更新时间:2023-11-28 07:09:39 26 4
gpt4 key购买 nike

我正在尝试编写一个 cpp 程序来执行带有运算符重载的矩阵运算。

我的类 Matrix 有以下变量:

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::operator=(const 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;
}

赋值运算符的签名错误,因此 return *this 试图调用 Matrix(Matrix) 类型的构造函数,该构造函数不存在。确保像上面那样返回引用。

关于c++ - 使用赋值运算符导致编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21215490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com