在C ++中调用+ =运算符函数内的Operator +函数

时间:2016-02-27 00:40:40

标签: c++

我在下面有这个重载+运算符函数,我必须编写另一个重载+ =运算符函数。我想知道我是否可以在= +运算符函数中调用+运算符函数,因为基本上这两个函数都在做同样的事情。如果是这样,那么它的语法是什么样的?

下面是我的+操作员功能。我试图添加2个动态分配的矩阵。

  Matrix Matrix::operator + (const Matrix & orig) const
  {
      int length = columns * rows; 
      try
      {
          if (rows != orig.rows || columns != orig.columns)
          {
              throw 1;
          }
     }
      catch (int c)
      {
          if (c == 1)
          {
              cout << "Error. Check Matrix dimensions, they do not match." << endl; 
          }
      }
      Matrix x(rows, columns);
      for (int i = 0; i < length; i++)
      {
          x.data[i] = data[i] + orig.data[i];
      }
      return x;
  }

 void Matrix::operator += (const Matrix & orig)
 {
    //just call the + operator function! 
 }

3 个答案:

答案 0 :(得分:2)

是的,你可以,你可以让你的函数返回一个矩阵:

*this = *this + orig;
return *this;

答案 1 :(得分:1)

您可以像在其他地方一样调用+运算符。这里的一个操作数当然是参数orig,而另一个操作数是你自己调用操作符的对象,即*this

所以你可以写:

*this = *this + orig

使用operator+=来定义operator+是否明智,或者更好的做法是反过来取决于您并可能取决于您的实施。

然而,将+ =运算符定义为

通常是个好主意
Matrix& Matrix::operator+= (const Matrix & orig)

因为你可以做像

这样的事情
mat += otherMat += otherMat2;

为此,只需返回*this,就像Stefan Giapantzakis已经指出的那样。

答案 2 :(得分:1)

这很简单:只需*this = *this + other

但是,通常最好完全编写operator+=然后operator+编写+=,如下所示:

Matrix& Matrix::operator+=(const Matrix &rhs) {
  try {
    if (rows != orig.rows || columns != orig.columns)
      throw "Error. Check Matrix dimensions, they do not match.";
  } catch (char const* msg) {
    std::cout << msg << std::endl; 
  }
  int length = columns * rows; 
  for (int i = 0; i < length; i++) {
    data[i] += orig.data[i];
  }
  return *this;
}
friend Matrix operator+(Matrix lhs, Matrix const& rhs){
  lhs += rhs;
  return std::move(lhs);
}

作为奖励,减少a+b+c+d以创建一个非移动构造的矩阵。

相关问题