您的代碼會忽略表達式c1+c2
的值,因爲您沒有將它存儲在任何位置。編譯器至多會打印一些警告消息。爲了剿這樣的警告信息,你可以寫:
(void)(c1+c2); //casting to void suppresses the warning messages!
看到這個:
與您的代碼真正的問題..
然而,在你的代碼中,operator+
的實現在語義上不是c orrect。據瞭解,考慮這個,
int a=10;
int b=5;
那麼,你希望a+b
改變a
價值? a
應該變成15
?號碼
如果你想要的話,那麼你會寫a+=b
來代替。但在您的代碼中,c1+c2
的行爲等同於c1+=c2
的語義,因爲您在執行operator+
時更新了this->real
和this->imag
的值,這在語義上是不正確的。
所以第一個解決方法是這樣的:
complex complex::operator + (const complex& c) const
{
complex result(c); //make a copy of c
result.real += this->real; //add
result.imag += this->imag; //add
return result;
}
現在,這是語義正確的。
這就是說,還有幾件事值得注意。當你寫c1+c2
時,你認爲操作+
是應用於任何一個對象嗎?不。它不適用於它們中的任何一個,但成員函數operator+
在c1
對象上被調用,該對象在函數內變成this
指針。爲什麼要在c1
(或者對於c2
)調用它,如果該操作不適用於它?
此分析表明operator+
不應該是該類的成員函數。這應該是一個非成員函數代替,然後簽名是:
complex operator+(const complex &a, const complex &b);
但有一個小問題:在a+b
計算,它需要訪問類的私有成員(real
和imag
是私人成員)。因此該解決方案是,operator+
應在operator+=
方面來實現,並且後者應該被添加爲成員函數到類,因爲在表達式a+=b
操作+=
不上a
適用,因爲它修改它的值。
因此,這裏是我的實現無論是運營商的:
class complex
{
//...
public:
//member function
complex& operator+=(const complex & c)
{
real += c.real; //same as: this->real+=c.real; this is implicit
imag += c.imag; //same as: this->imag+=c.real; this is implicit
return *this;
}
};
//non-member function (its non-friend as well)
complex operator+(const complex &a, const complex &b)
{
complex result(a); //make copy of a by invoking the copy-constructor
result += b; //invokes operator+
return result;
}
或者你可以參加最後兩個語句:
complex operator+(const complex &a, const complex &b)
{
complex result(a); //make copy of a by invoking the copy-constructor
return result += b; //invokes operator+, and then return updated 'result'
}
但還有另一種方法,使副本。爲什麼通過引用傳遞兩個參數?按值傳遞第一個參數將會生成我們需要的副本。所以更好的實施將是這樣的:
complex operator+(complex a, const complex &b)
{ //^^^^^^^^^ pass-by-value
a += b; //a is a copy, after all - we can modify it!
return a;
}
希望有所幫助。
不要重載'運算符+'那樣。你能想象如果說'y = x + 7'修改了'x'的值嗎? –
@Travis ..感謝您的建議:) ..我明白了。但我是C++的初學者,並試圖以各種方式探索事物。 – jsp99
挑剔。不要通過按值傳遞rhs來重載+運算符。通過參考傳遞。那就是將函數聲明爲「complex&complex :: operator +(complex&c)」。 – selbie