2015-11-05 64 views
0

我試圖重載==操作符,然後用主函數中的代碼對其進行測試。它給了我一個錯誤,並說我的if語句中的z必須是bool類型或轉換爲一個。我只是想知道我在哪裏出了問題,怎麼去設置這個部分。這是代碼片段。我宣佈雙重真實&作爲私有變量也是雙重想象。C++ Overloading ==複數

Complex Complex::operator==(const Complex &operand2) const 
{ 
if (real == operand2.real, imaginary == operand2.imaginary) 
    return true; 
else 
    return false; 
} 
int main() 
{ 
Complex x(1, 2); 
Complex y(2, 3); 
Complex z, w, v; 

z = x + y; 
w = x – y; 

if (z == w) 
    cout << " z = w" << endl; 
else 
    cout << " z != w" << endl; 

return 0; 

}

回答

1

該代碼將是這樣的:

bool Complex::operator==(const Complex &operand2) const 
{ 
    return (real == operand2.real && imaginary == operand2.imaginary) ; 
} 
  1. 的返回類型應該是bool因爲結果總是truefalse
  2. 由於實部和虛部都需要相等,因此使用&&(AND)操作來加入這兩個條件。

還要注意,涉及==操作者的任何操作將返回一個bool值(truefalse)和因此而不是if條件,可以直接返回結果。

+0

嗯是一個愚蠢的錯誤,完全滑倒在返回類型的我的頭腦,謝謝! – John

0

你的收益從您的運營商bool,那麼還有什麼你希望

0

如果定義操作返回值作爲複雜的,你不能返回布爾值。

Complex Complex::operator==/*...*/ 

這實際上返回Complex類型,這是沒有問題的,除非你需要bool值。

bool Complex::operator== 

所以回到這裏的類型是你想要的。欲瞭解更多信息,請閱讀此:http://en.cppreference.com/w/cpp/language/operators