【问题标题】:how to apply operator overloading for unary postfix operator如何为一元后缀运算符应用运算符重载
【发布时间】:2022-11-18 14:39:44
【问题描述】:

下面是一元运算符++的运算符重载代码

#include <iostream>
using namespace std;
 
class Distance {
   private:
      int feet;             // 0 to infinite
      int inches;           // 0 to 12
      
   public:
      // required constructors
      Distance() {
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i) {
         feet = f;
         inches = i;
      }
      
      // method to display distance
      void displayDistance() {
         cout << "F: " << feet << " I:" << inches <<endl;
      }
      
      // overloaded minus (-) operator
      Distance operator++ () {
         feet = feet+1;
         inches = inches+1;
         
         return Distance(feet, inches);
      }
};

int main() {
   Distance D1(11, 10), D2(-5, 11);
 
   ++D1;                     // increment by 1
   
   D1.displayDistance();    // display D1

   ++D2;                     // increment by 1
   D2.displayDistance();    // display D2

   return 0;
}

当我使用上面的代码时,我可以成功地使用前缀运算符 ++D1 和 ++D2 但我不知道如何重载后缀运算符 D1++ 和 D2++ 即使我在上面的代码中尝试这些,它也会显示错误 那么我们如何分别对后缀和前缀使用运算符重载的概念呢?

【问题讨论】:

    标签: c++ operator-overloading prefix postfix-notation


    【解决方案1】:

    对于后缀 operator++,您必须指定一个类型为 int 的额外(未使用)参数,如下所示:

    class Distance {
       
          //other code as before
          public:
          Distance operator++(int);//declaration for postfix operator++
    };
    
    //other code as before 
    
    //definition for postfix operator++
    Distance Distance::operator++(int)
    {    
        Distance ret = *this;   // save the current value
        
        ++*this;     // use prefix ++
        return ret;  // return the saved state
    }
    

    DEMO

    解释

    有一个问题在同时定义前缀和后缀运算符时,因为这两个版本使用相同的符号,这意味着这些运算符的重载版本具有相同的名称。此外,它们还具有相同数量和类型的操作数。

    所以要解决这个问题,postfix 版本采用int 类型的额外参数。当我们使用后缀运算符时,编译器会自动/隐式提供 0 作为此参数的实参。

    【讨论】:

      【解决方案2】:

      如果你想要 post-inc/dec 那么代码将是:

        Distance operator++ (int) {
           feet = feet+1;
           inches = inches+1;
           
           return Distance(feet, inches);
        }
      

      我们在形式参数中使用int。它只是板条箱在后/预修复之间有所不同。 运算符的前缀形式的声明方式与任何其他一元运算符完全相同;后缀形式接受一个额外的 int 类型参数。

      【讨论】:

      • 您的代码具有不正确的后缀增量语义。
      猜你喜欢
      • 2014-11-18
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      相关资源
      最近更新 更多