카테고리 없음

단항 연산자 오버로딩과 전위 연산, 후위 연산

zuyo 2019. 5. 9. 02:08
반응형

단항 연산자오버로딩

#include <iostream>
using namespace std;

class Point {
private:
	int xpos, ypos;

public:
	Point(int x, int y) : xpos(x), ypos(y) { }

	void ShowPositionInfo() {
		cout << "[ " << xpos << ", " << ypos << " ]" << endl;
	}

	Point& operator++() {
		xpos++;
		ypos++;
		return *this;
	}

	friend Point& operator--(Point& pos);
};

Point& operator--(Point& pos) {
	pos.xpos--;
	pos.ypos--;

	return pos;
};

void main() {
	Point pos1(3,4);
	pos1++;
	pos1.ShowPositionInfo();
	pos1--;
	pos1.ShowPositionInfo();
}

전위 연산, 후위 연산 

cout << num++ << endl; // 출력 후 값 증가 (후위 연산)
cout << ++num << endl; // 값 증가 후 출력 (전위 연산)

전위 연산 ++pos를 pos.operator++()로 정의하고
후위 연산 pos++를 pos.operator++(int)로 정의한다.(후위연산을 구분하기 위해 괄호에 자료형이 들어간다)

1. 전위연산

Point& operator++() {
     xpos+=1;
     ypos+=1;
     return *this;
}

2. 후위연산

const Point operator++(int) {
     const Point retobj(xpos, ypos); // const 객체
     xpos+=1;
     ypos+=1;
     return retobj; // 연산이 되지 않은 결과 반환
}
반응형