Latest web development tutorials

C ++ operator overloading relationship

C ++ function overloading and operator overloading C ++ function overloading and operator overloading

C ++ language supports a variety of relational operators (<,>, <=,> =, ==, etc.), they can be used to compare the C ++ built-in data types.

You can override any of the relational operators, the overloaded relational operators can be used to compare objects of the class.

The following example demonstrates how overloaded <operator. Similarly, you can also try other overloaded relational operators.

#include <iostream>
using namespace std;
 
class Distance
{
   private:
      int feet;             // 0 到无穷
      int inches;           // 0 到 12
   public:
      // 所需的构造函数
      Distance(){
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i){
         feet = f;
         inches = i;
      }
      // 显示距离的方法
      void displayDistance()
      {
         cout << "F: " << feet << " I:" << inches <<endl;
      }
      // 重载负运算符( - )
      Distance operator- ()  
      {
         feet = -feet;
         inches = -inches;
         return Distance(feet, inches);
      }
      // 重载小于运算符( < )
      bool operator <(const Distance& d)
      {
         if(feet < d.feet)
         {
            return true;
         }
         if(feet == d.feet && inches < d.inches)
         {
            return true;
         }
         return false;
      }
};
int main()
{
   Distance D1(11, 10), D2(5, 11);
 
   if( D1 < D2 )
   {
      cout << "D1 is less than D2 " << endl;
   }
   else
   {
      cout << "D2 is less than D1 " << endl;
   }
   return 0;
}

When the above code is compiled and executed, it produces the following results:

D2 is less than D1

C ++ function overloading and operator overloading C ++ function overloading and operator overloading