2014-10-17 37 views
0

我正在嘗試使用已編寫的+運算符函數爲C++類的+=運算符編寫函數。到目前爲止,我還沒有成功將this指針與+運算符關聯起來。這些是我在g++編制的一些嘗試,但沒有產生期望的結果。我兩次嘗試簡單地製作this課程的副本,但看起來並不奏效。C++類:在成員函數內創建「this」類的副本

intstr& intstr::operator+=(const intstr& i) 
{ 
    intstr *a; 
    a = new intstr; 
    *a = *this + i; 
    return *a; 
} 
intstr& intstr::operator+=(const intstr& i) 
{ 
    intstr *a, b(*this); 
    a = new intstr; 
    *a = b + i; 
    return *a; 
} 
intstr& intstr::operator+=(const intstr& i) 
{ 
    intstr *a, *b; 
    a = new intstr; 
    b = this; 
    *a = *b + i; 
    return *a; 
} 
intstr& intstr::operator+=(const intstr& i) 
{ 
    intstr *a; 
    a = new intstr; 
    *a = this->operator+(i); 
    return *a; 
} 

在測試代碼,所有我所做的是a += i替換代碼a = a + i工作線,所以我懷疑問題出在那裏,但它是可能的。是否只有這樣才能將代碼從+運算符複製到+=函數中?

+0

可能的複製(推薦閱讀反正):http://stackoverflow.com/questions/4421706/operator-overloading – JBentley 2014-10-17 04:27:58

回答

1

運營商可以像

intstr& intstr::operator+=(const intstr& i) 
{ 
    *this = *this + i; 

    return *this; 
} 

如果operator +被聲明爲一個類的成員函數,那麼你也可以寫

intstr& intstr::operator+=(const intstr& i) 
{ 
    *this = operator +(i); // or *this = this->operator +(i); 

    return *this; 
} 

動態分配運算符中的intstr對象將是一個錯誤。至少不需要這樣做。

+0

謝謝,這工作!我知道必須有一個簡單的方法來做到這一點。 – 2014-10-17 04:28:33

+0

@Vlad如果我們使用return(operator +(i)),它也可以; ? – 2014-10-17 07:46:38

+0

@sameer karjatkar不,它不會o'k。 Operator +可能不會更改左操作數。它可能會返回一個臨時對象,即使是一個const臨時對象。 – 2014-10-17 07:49:11

2

通常情況下,方法是相反的:您實現了operator+=,然後使用該實現實現了operator+(創建第一個參數的副本,然後使用+=增加第二個參數並返回該參數)。

除此之外,你爲什麼要在所有版本中調用new?對於operator+=,您根本不需要創建任何新對象。操作員應該通過用右側的值增加左側操作數的值來修改其值。沒有新的對象需要在任何地方創建(而較少動態地new分配!)

+0

謝謝你的回覆快!起初,我並不認爲我需要「新」,但直到我用它來編譯我的代碼,所以我只是隨它而去。我從來沒有想過首先使用「+ =」,並從中推導出「+」 - 很好知道!我會嘗試的。 – 2014-10-17 04:25:08

0

通常你做它周圍的其他方法:

intstr& intstr::operator+=(intstr const& rhs) 
{ 
    // Do this stuff to add rhs into this object. 
    return *this; 
} 

// Then + is implemented in terms of += 
intstr intstr::operator+(intstr const& rhs) 
{ 
    instr result(*this); // Make a copy as the result 
    result += rhs; 
    return result; 
} 

// Then your free functions as needed. 
+0

我不確定..你不覺得結果對象會在運算符函數結束時被銷燬嗎? – 2014-10-17 10:05:46

+0

@sameerkarjatkar:不會,它會被返回值。請記住,'operator +'會創建一個新值,通過值返回以將其從函數中移出。 – 2014-10-17 15:11:04