2015-11-05 45 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