2016-02-27 85 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一個矩陣不動構造。