C++ 运算符重载时,将运算符两边对象交换问题.

时间:2021-05-23 17:34:59

在C++进行运算符重载时, 一般来讲,运算符两边的对象的顺序是不能交换的. 比如下面的例子:

#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+ (int i)  
      {
         feet = feet + i;
         inches = inches + i;
         return Distance(feet, inches);
      }
     

};
int main()
{
   Distance D1(11, 10), D2(5, 11);
 
   Distance D3 , D4;
   D3 = 3 + D1;
   D4 = D1 + 3;
   D3.displayDistance();
   D4.displayDistance();

   if( D2 < D1 )
   {
      cout << "D1 is less than D2 " << endl;
   }
   else
   {
      cout << "D2 is less than D1 " << endl;
   }
   return 0;
}

在重载加号'+'运算符时, D4 = D1 + 3 是正确的, 而D3 = 3 + D1 提示出错. 

解决该问题的一个方法是声明一个友元函数. 如下所示:

#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+ (int i)  
      {
         feet = feet + i;
         inches = inches + i;
         return Distance(feet, inches);
      }
    

        friend Distance operator+ (int i, const Distance& D)
        {
                Distance d;
                d.feet = D.feet + i;
                d.inches = D.inches + i;
                return Distance(d.feet, d.inches);

        }
};
int main()
{
   Distance D1(11, 10), D2(5, 11);
 
   Distance D3 , D4;
   D3 = 3 + D1;
   D4 = D1 + 3;
   D3.displayDistance();
   D4.displayDistance();

   if( D2 < D1 )
   {
      cout << "D1 is less than D2 " << endl;
   }
   else
   {
      cout << "D2 is less than D1 " << endl;
   }
   return 0;
}

这时便能过通过编译,顺利执行了.