2016-02-27 46 views
0

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

1)是的,你可以。 2)你通常会怎么称呼操作员+功能? – immibis

+2

这是一个相当无用的try/catch块,因为你所做的只是在继续之前写入stdout。操作符+和操作符+ =之间存在语义差异,因为前者返回一个新对象,+ =正在修改它。 –

+3

通常情况下,你可以用相反的方法:写'operator + =',并根据它定义'operator +'。 –

回答

2

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

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

感谢这工作! – ashketchumall

1

你可以简单地调用+运营商,你会做其他任何地方。这里的一个操作数当然是参数orig,而另一个操作数是您自己调用操作员的对象,即*this

所以,你可以这样写:

*this = *this + orig 

无论是明智的使用operator+或者其更好地做到这一点倒过来是给你和可能取决于你的实现operator+=定义。

但是它通常是一个好主意,定义+ =操作员

Matrix& Matrix::operator+= (const Matrix & orig) 

,因为你就可以做这样的事情

mat += otherMat += otherMat2; 

对于这一点,只是返回*this为斯特凡Giapantzakis已经指出出。

+0

嘿,谢谢这工作后,我改变了:无效矩阵::运算符+ =(矩阵矩阵&原始)矩阵矩阵::运算符+ =(常量矩阵&原始) – ashketchumall

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); 
} 

其中,作为奖励,reduxes a+b+c+d到创建exacly一个矩阵不动构造。