Reputation: 39
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
Reputation: 3295
The code will be something like this :
bool Complex::operator==(const Complex &operand2) const
{
return (real == operand2.real && imaginary == operand2.imaginary) ;
}
bool
as the result is always true
or false
.&&
(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
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
Reputation: 8354
Your return a bool
from your operator ,so what else do you expect
Upvotes: 0