Reputation: 41
My assignment is having us overload the ==
, <
, and >
operators. I understand that operator overloading essentially overrides the code of an operator. I have found a way to overload the +
and -
operators. My problem appears when I try to overload the ==
operator. Maybe I am going about this wrong, but I am trying to make a function to return a string saying that they are equal or not.
Temperature operator == (Temperature const &temp1, Temperature const &temp2)
{
int holder;
if(temp1 == temp2)
{
holder = 1;
}
return holder;
}
I also tried to return 1 so that I could make a if statement in the main function to check if their equal or not.
Temperature operator == (Temperature const &temp1, Temperature const &temp2)
{
string holder;
if(temp1 == temp2)
{
holder = "temp1 is equal to temp2";
}
return holder;
}
I know that there's not much difference between the attempts but I'm struggling to find ways to go about it.
Upvotes: 1
Views: 184
Reputation: 14589
Your code got three problems. First, you're trying to compare two objects by calling compare operator within compare operator for those two objects (ie. calling itself). Second, you're returning an object value instead of bool
. An you're returning uninitialized value when comparison failed.
It's obvious from your code, that Temperature
is context-convertible from int
, i.e., it's some integral type, in this case overload causes problems. You have to have an unambiguous overload.
In general, free-standing operator==
for MyClass
may look something like this:
bool operator == (MyClass const &a1, MyClass const &a2)
{
return (a1.value1 == a2.value1) && (a1.value2 == a2.value2);
}
It should be a friend function or have access to members of class, of course.
The point of overloading operators is to define them for particular type(s) of parameters. They are functions, just like any other overloaded function and must be distinctive from other instances of that operator. They may introduce a new behavior (example: << and >> operators of <iostream>
), or just provide implied behavior. Exclusions are new\delete and type conversion operators.
Upvotes: 2
Reputation: 16670
Your operator is returning the wrong type. It should look like this:
bool operator == (Temperature const &temp1, Temperature const &temp2)
return true
if the two compare equal, false
otherwise.
Upvotes: 4