class Point
{
private:
int xpos;
int ypos;
public:
Point(int x, int y) :xpos(x), ypos(y)
{ }
Point& operator++()
{
xpos+=1;
ypos+=1;
return *this;
};
Point&를 반환형으로 하는 이유는 ++(++obj1)과 같은 연산도 구현하기 위해서다.
++(++obj1) -> ++(obj1.operator++()) -> ++(obj1의 참조값) 순으로 연산된다.
후위 증감 연산자의 경우 매개변수로 int를 하나 더 받는다.
이를 이용해 오버로딩을 구분한다.
const 객체 : 멤버변수의 변경 불가
const참조자로만 참조가능
const 객체는 const멤버함수만 호출가능
반환형이 const : 반환되는 객체를 const화 하겠다는 의미
class Point
{
private:
int xpos;
int ypos;
public:
Point(int x, int y) :xpos(x), ypos(y)
{ }
const Point& operator++(int)
{
Point rpos(xpos, ypos);
xpos+=1;
ypos+=1;
return rpos;
};
int main()
{
Point obj1(1,1);
obj1++;
//(obj1++)++; error
후위 증감연산자의 반환형을 const로 한 이유는 (obj1++)++가 오류가 나도록 하기 위해서다.
obj1++로 반환된 임시객체로 operator++를 더 호출하지 못하도록해 논리적 오류가 발생하지 않도록 한다.