Latest web development tutorials

C ++ unary operator overloading

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

Unary operators only one operand operation, the following are examples of unary operators:

Unary operator typically appears at the left of the object on which they operate, for example! Obj, -obj and ++ obj, but sometimes they can also be used as a suffix, such as obj ++ or obj--.

The following example demonstrates how overloaded unary minus operator (-).

#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);
      }
};
int main()
{
   Distance D1(11, 10), D2(-5, 11);
 
   -D1;                     // 取相反数
   D1.displayDistance();    // 距离 D1

   -D2;                     // 取相反数
   D2.displayDistance();    // 距离 D2

   return 0;
}

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

F: -11 I:-10
F: 5 I:-11

I hope the above examples can help you better understand the unary operator overloading concept, similarly, you can try to reload the logical NOT operator (!).

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