C++ : 연산자 오버로딩(4) - 전위증가, 후위증가
참고 : 열혈강의 C++ 프로그래밍 책
#includeusing namespace std; class OperPoint3 { private: int x, y; public: OperPoint3(int px = 0, int py = 0) : x(px), y(py) { } void ShowPosition() const { cout << '[' << x << ", " << y << ']' << endl; } // 전위 증가 OperPoint3& operator++() { x += 1; y += 1; } // 후위 증가 // 후위 연산자만 const 반환형인 이유는 // C++연산 특성과 똑같이 해서 (pos++)++; 사용시 컴파일 에러를 유발하기 위함 const OperPoint3 operator++(int) { // const Point retobj(*this) 와 같다. const OperPoint3 retobj(x, y); x += 1; y += 1; return retobj; } friend OperPoint3& operator--(OperPoint3 &ref); friend const OperPoint3 operator--(OperPoint3 &ref, int); }; // 전위 감소 OperPoint3& operator--(OperPoint3 &ref) { ref.x -= 1; ref.y -= 1; return ref; } // 후위 감소 // 후위 연산자만 const 반환형인 이유는 // C++연산 특성과 똑같이 해서 (pos++)++; 사용시 컴파일 에러를 유발하기 위함 const OperPoint3 operator--(OperPoint3 &ref, int) { const OperPoint3 retobj(ref); ref.x -= 1; ref.y -= 1; return retobj; } // 테스트 OperPoint3 pos(3, 5); OperPoint3 cpy; cpy = pos--; cpy.ShowPosition(); pos.ShowPosition(); cpy = pos++; cpy.ShowPosition(); pos.ShowPosition(); int num = 100; ++(++num); --(--num); // 컴파일 에러 - 위에서 말한 const 반환을 쓰는 이유 (num++)++; (num--)--;
댓글
댓글 쓰기