c ++重载==复数

时间:2015-11-05 04:32:34

标签: operator-overloading

我试图重载==运算符,然后使用main函数中的代码对其进行测试。它给了我一个错误,并说我的if语句中的z必须是bool类型或转换为一个。我只是想知道我在哪里出错,以及如何设置这部分。这是代码片段。我宣布双重真实&双重虚构作为私人变量。

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;

}

3 个答案:

答案 0 :(得分:1)

代码将是这样的:

bool Complex::operator==(const Complex &operand2) const
{
    return (real == operand2.real && imaginary == operand2.imaginary) ;
}
  1. 返回类型应为bool,因为结果始终为truefalse
  2. 由于实部和虚部都需要相等,因此使用&&(AND)运算来加入这两个条件。
  3. 另请注意,涉及==运算符的任何操作都将返回bool值(truefalse),因此而不是if条件,你可以直接返回结果。

答案 1 :(得分:0)

您从运营商处返回Bullet.prototype = { render: function () { ctx.fillStyle = this.color; ctx.arc(this.coordinates.x, this.coordinates.y, this.size.radius, 0, Math.PI * 2, false); ctx.fill(); return this; }, animate: function () { this.coordinates.x += this.velocity.speed.x; return this; } }; ,那么您还有什么期望

答案 2 :(得分:0)

如果将运算符返回值定义为复数,则无法返回布尔值。

['2015-08-07', '70']
['2015-08-08', '82']
['2015-08-09', '91']
['2015-08-10', '84']
['2015-11-03', '']
['2015-11-05', '']

除非你需要bool值,否则这实际上会返回没有问题的Complex Complex::operator==/*...*/ 类型。

Complex

所以返回类型就是你想要的。有关详细信息,请阅读:http://en.cppreference.com/w/cpp/language/operators