遞增和遞減運算子多載 (C++)

遞增和遞減運算子屬於特殊的分類,因為每個運算子都有兩種變數:

  • 前置遞增和後置遞增

  • 前置遞減和後置遞減

當您撰寫多載運算子函式時,分別針對這些運算子實作前置和後置的不同版本可能會很有用。 為了區分這兩者,觀察到下列規則:運算子的前置詞形式與任何其他一元運算子完全相同:後置表單接受 類型 int 的額外引數。

注意

為遞增或遞減運算子的後置格式指定多載運算子時,其他引數的類型必須為 int ;指定任何其他類型會產生錯誤。

下列範例顯示如何為 Point 類別定義前置和後置遞增及遞減運算子:

// increment_and_decrement1.cpp
class Point
{
public:
   // Declare prefix and postfix increment operators.
   Point& operator++();       // Prefix increment operator.
   Point operator++(int);     // Postfix increment operator.

   // Declare prefix and postfix decrement operators.
   Point& operator--();       // Prefix decrement operator.
   Point operator--(int);     // Postfix decrement operator.

   // Define default constructor.
   Point() { _x = _y = 0; }

   // Define accessor functions.
   int x() { return _x; }
   int y() { return _y; }
private:
   int _x, _y;
};

// Define prefix increment operator.
Point& Point::operator++()
{
   _x++;
   _y++;
   return *this;
}

// Define postfix increment operator.
Point Point::operator++(int)
{
   Point temp = *this;
   ++*this;
   return temp;
}

// Define prefix decrement operator.
Point& Point::operator--()
{
   _x--;
   _y--;
   return *this;
}

// Define postfix decrement operator.
Point Point::operator--(int)
{
   Point temp = *this;
   --*this;
   return temp;
}

int main()
{
}

您可以使用下列函式原型,在檔案範圍(全域)中定義相同的運算子:

friend Point& operator++( Point& );      // Prefix increment
friend Point operator++( Point&, int );  // Postfix increment
friend Point& operator--( Point& );      // Prefix decrement
friend Point operator--( Point&, int );  // Postfix decrement

型別的 int 引數,表示遞增或遞減運算子的後置格式,通常不會用來傳遞引數。 它通常包含值 0。 不過,可以依如下的方式使用:

// increment_and_decrement2.cpp
class Int
{
public:
    Int operator++( int n ); // Postfix increment operator
private:
    int _i;
};

Int Int::operator++( int n )
{
    Int result = *this;
    if( n != 0 )    // Handle case where an argument is passed.
        _i += n;
    else
        _i++;       // Handle case where no argument is passed.
    return result;
}

int main()
{
   Int i;
   i.operator++( 25 ); // Increment by 25.
}

沒有使用遞增或遞減運算子傳遞這些值以外的明確調用語法,如上述程式碼所示。 實作這項功能的更直接方式是多載加法/指派運算子 ( += )。

另請參閱

運算子多載