nakka soft world !

증가/감소 연산자 재정의 본문

프로그래밍언어/C++

증가/감소 연산자 재정의

nakka 2017. 3. 19. 02:26
728x90

증가/감소 연산자 재정의


class Integer

{

private:

int value;

public:

Integer(int n = 0) : value(n) {}

void print() const { cout << vlaue << endl; }

};

int main()

{

int 1; // 초기화 하지 않아 쓰레기값 출력

Integer n2; // 0으로 초기화 됨


++n2;


n2.print();

}





class Integer

{

private:

int value;

public:

Integer(int n = 0) : value(n) {}

void print() const { cout << vlaue << endl; }

};

int main()

{

Integer n(3);

++n;      //  n.operator++();  // 멤버함수

 // operator++(n);   // 일반함수

// 수행하고 난 뒤 자신의 상태가 변경됨. private의 값을 바꿔야함. 즉 멤버 함수가 더 좋을 것으로 보임.


n2.print();

}



전위형, 후위형.

class Integer

{

private:

int value;

public:

Integer(int n = 0) : value(n) {}

void print() const { cout << vlaue << endl; }

//Integer operator++() // 임시객체

Integer& operator++()

{

++value;

return *this;

}

// 후위형

Integer operator++(int )

{

Integer temp = *this;

//++value;

++(*this); // 후위형의 구현은 전위형을 사용해서 구현하자.

return temp;

}

};

int main()

{

Integer n(3);

++(++n);   // ++(임시객체) // 5를 기대 했으나 4가 나옴. 리턴값을 값이 아닌 참조를 넘겨야 함.

n.print();

}


함수 객체 (function obkect, fnction)

int main()

{

for(int i =; i<10; i++)  // i++보다는 ++i가 성능상 더 좋음. 그러나 요즘 컴파일러는 자동으로 변환해줌.

}


728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

스마트 포인터 (Smart Pointer)  (0) 2017.03.19
함수 객체(function object, fonctor)  (0) 2017.03.19
cout & ostream  (0) 2017.03.19
연산자 재정의 개념  (0) 2017.03.19
this  (0) 2017.03.19
Comments