【问题标题】:Using assignment operator causes compiler error使用赋值运算符会导致编译器错误
【发布时间】: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&amp;) 我强烈怀疑你想要那个。也许是const
  • 其他函数的参数也应该使用const&amp;,以避免不断复制矩阵。
  • Matrix Matrix::operator=(Matrix a)... return *this; 是不是错了?它需要一个 Matrix(Matrix) 构造函数
  • 如果本练习的目的是学习如何正确编写矩阵类和重载运算符,只需抛弃手动内存管理并使用 std::vector&lt;std::vector&lt;int&gt;&gt; 即可。另一方面,如果练习的目的是学习如何在 C++ 中管理资源,请阅读三法则(C++ 11 中的五法则)、RAII,最后阅读零法则(在那请订购)。
  • 对于运算符重载,wiki 有一个关于该主题的非常好的线程。此外,三/五规则是许多问题都涉及的主题,因此这绝对是重复的。

标签: c++ matrix operator-overloading dynamic-allocation


【解决方案1】:
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) 类型的构造函数。确保返回类似上面的引用。

【讨论】:

  • 除非你使用复制和交换习语,否则参数应该作为const&amp;传递。
  • @Manu343726 抱歉复制和粘贴工作,已修复
【解决方案2】:

除了其他关于有效实现复制构造函数和赋值操作符的答案(你的代码不是很有效,但它应该可以工作),似乎只有一个小错误:

Matrix(Matrix&amp; other) { ... } 似乎超出了命名空间。将其更改为:

Matrix::Matrix(const Matrix&amp; other) { ... }

【讨论】:

  • 可能在类定义中,但 OP 反应不是很好
猜你喜欢
  • 2017-04-30
  • 1970-01-01
  • 2019-04-06
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 2010-09-27
  • 2017-02-22
相关资源
最近更新 更多