250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/9.05] 증감 연산자 오버로딩 본문

C++/따배C++ 09강 연산자 오버로딩

[C++/9.05] 증감 연산자 오버로딩

polarcompass 2021. 10. 29. 01:31
728x90

증감 연산자 작동 원리를 이 예제를 통해 확인 할 수 있다.

#include<iostream>
using namespace std;

class Digit
{
private:
    int m_digit;
public:
    Digit(int digit = 0)
        : m_digit(digit)
    {}

    // prefix
    Digit &operator ++ ()
    {
        ++m_digit;
        return *this;
    }

    // postfix
    Digit operator ++ (int)
    {
        Digit tmp{m_digit};
        ++(*this);
        return tmp;
    }

    friend ostream &operator << (ostream &out, const Digit &d)
    {
        out << d.m_digit;
        return out;
    }
};

int main()
{
    Digit d{5};

    // prefix
    cout << ++d << endl;
    cout << d << endl;

    // postfix
    cout << d++ << endl;
    cout << d << endl;

    return 0;
}
728x90