John
John

Reputation: 39

c++ Overloading == for complex numbers

I am attempting to overload the == operator then test it with the code in the main function. It gives me an error and says the z in my if statement must be a bool type or converted into one. I am just wondering where I am going wrong here and how to go about setting that part up. Here is the code snippet. I declared double real & double imaginary as private variables also.

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;

}

Upvotes: 0

Views: 2018

Answers (3)

a_pradhan
a_pradhan

Reputation: 3295

The code will be something like this :

bool Complex::operator==(const Complex &operand2) const
{
    return (real == operand2.real && imaginary == operand2.imaginary) ;
}
  1. The return type should be bool as the result is always true or false.
  2. Since both the real and imaginary parts need to be equal, you use && (AND) operation to join the two conditions.

Also notice that any operation involving the == operator will return a bool value (either true or false) and hence instead of a if condition, you can directly return the result.

Upvotes: 1

Lasoloz
Lasoloz

Reputation: 262

If you defined operator return value as complex you cannot return boolean.

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

This actually returns the Complex type which is not problem, unless you need bool value.

bool Complex::operator==

So return type here is what you want. For further information read this: http://en.cppreference.com/w/cpp/language/operators

Upvotes: 0

Ramanlfc
Ramanlfc

Reputation: 8354

Your return a bool from your operator ,so what else do you expect

Upvotes: 0

Related Questions