【问题标题】:How to overload + to sum 2 objects that are matrix in c++?如何重载 + 以求和 2 个 C++ 中的矩阵对象?
【发布时间】:2020-05-10 21:24:34
【问题描述】:

我有这门课

class Matrix
{
    int size;

    std::unique_ptr<std::unique_ptr<int[]>[]>  val;

public:

    Matrix(int size1)
    {
        size=size1;
        val=std::make_unique< std::unique_ptr<int[]>[] >(size);

        ...
    }

...移动构造函数,移动赋值运算符

    Matrix& operator+(Matrix &m)
    {
        Matrix sumMatrix(size);
        for ( int i = 0; i < size; ++i)
        {
            for (int j = 0; j < size; ++j){
                sumMatrix.val[i][j]=this->val[i][j]+m.val[i][j];
            }

        }
        return sumMatrix;
    }

和主要的:

...
Matrix e=b+c;
    std::cout<<"e="<<std::endl;
    e.print();

我有这个错误:

警告:返回对局部变量“sumMatrix”的引用 [-Wreturn-local-addr] 矩阵 sumMatrix(size);

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 应该读到这个:What are the basic rules and idioms for operator overloading?,尤其是算术运算部分。
  • Matrix&amp; operator+(Matrix &amp;m); 应该是Matrix operator+(const Matrix &amp;m) const; 此外,您可能还需要检查m 的大小。假设它们的大小相同是有风险的。您可以将大小设为模板参数。

标签: c++ unique-ptr


【解决方案1】:

按值返回,正如您在大多数情况下对operator+ 所做的那样:

//   vvv--Removed &     vvvvv-----vvvvv--Const is more appropriate here
Matrix operator+(Matrix const &m) const { ... }

这将需要一个复制构造函数,请确保添加它。另请注意,您可能应该将您的 for 循环逻辑收集到 operator+= 并显着简化 operator+,同时为最终用户提供更多功能:

Matrix& operator+=(Matrix const& m) {
  for (int i = 0; i < size; ++i) {
    for (int j = 0; j < size; ++j) {
      //vvv--No need for this-> in C++    
      val[i][j] += m.val[i][j];
    }
  }
  return *this;
}

Matrix operator+(Matrix const& m) const {
  Matrix sumMatrix{m}; // requires a copy constructor.
  sumMatrix += *this;
  return sumMatrix;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 2016-07-25
    相关资源
    最近更新 更多