I am still new to C++ (programming in general)and forgive me if this question is stupid or has been asked numerously. Here is the question..Let's say there are two objects A and B under the same class.
e.g
class Fruit{
int apple;
int banana;
fruit(int x, int y){
apple=x;
banana=y;
}
}
Fruit A(1,1);
Fruit B(1,1);
If I want to check if content from Object A is the same as Object B's, do I have to compare every variablefrom A to B, or
if(Object A == Object B)
return true;
will do the job?
if(Object A == Object B)
return true;
will do the job? No it won't, it won't even compile
error: no match for 'operator==' (operand types are 'Fruit' and 'Fruit')
You need to implement a comparison operator==
, like
bool Fruit::operator==(const Fruit& rhs) const
{
return (apple == rhs.apple) && (banana == rhs.banana);
// or, in C++11 (must #include <tuple>)
// return std::tie(apple, banana) == std::tie(rhs.apple, rhs.banana);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With