STL源码剖析-increment/decrement/dereference操作符

来源:互联网 发布:node深入浅出在线阅读 编辑:程序博客网 时间:2024/06/05 06:30

#include <iostream>

using namespace std;

class INT
{
    friend ostream& operator<<(ostream& os, const INT& i);
public:
    INT(int i):m_i(i){};
    //前置式prefix:increment and then fetch
    INT& operator++()
    {
        ++(this->m_i);
        return *this;
    }
    //后置式postfix:fetch and then increment
    const INT operator++(int)
    {
        INT temp = *this;
        ++(*this);
        return temp;
    }
    //前置式prefix:decrement and then fetch
    INT& operator--()
    {
        --(this->m_i);
        return *this;
    }
    //后置式postfix:fetch and then decrement
    const INT operator--(int)
    {
        INT temp = *this;
        --(*this);
        return temp;
    }
    int& operator*() const
    {
        return (int&)m_i;
    }
private:
    int m_i;
};

ostream& operator<<(ostream& os, const INT& i)
{
    os<<'['<<i.m_i<<']';
    return os;
}

int _tmain(int argc, _TCHAR* argv[])
{
    INT I(5);
    cout<<I++;
    cout<<++I;
    cout<<I--;
    cout<<--I;
    cout<<*I;
    return 0;
}


原创粉丝点击