# 递增和递减运算符重载 (C++)

• 前置递增和后置递增

• 前置递减和后置递减

``````// 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 );
private:
int _i;
};

Int& Int::operator++( int n )
{
if( n != 0 )    // Handle case where an argument is passed.
_i += n;
else
_i++;       // Handle case where no argument is passed.
return *this;
}
int main()
{
Int i;
i.operator++( 25 ); // Increment by 25.
}
``````