Comparison between two objects under the same class

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.

eg

  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); 
}
链接地址: http://www.djcxy.com/p/73774.html

上一篇: 为什么operator ==不能自动为C ++中的嵌套类合成

下一篇: 两个对象在同一个类下的比较