증가 및 감소 연산자 오버로드(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.
}

앞의 코드와 같이 증분 또는 감소 연산자를 사용하여 명시적 호출 이외의 값을 전달하는 구문은 없습니다. 이 기능을 구현하는 보다 간단한 방법은 더하기/할당 연산자(+=)를 오버로드하는 것입니다.

참고 항목

연산자 오버로드