码迷,mamicode.com
首页 > 其他好文 > 详细

前置和后置自增以及解引用重载函数(++、--、*)

时间:2015-04-28 18:26:54      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

#include<iostream>
using namespace std;


class INT 
{
private:
    int m_i;


public:
    INT(int i):m_i(i){}
    // 区分前置和后置自增重载函数的区别是是否有参数,以及参数的个数
    // 如果是前置自增,比如++a,因为++符号前面没有变量,于是重载函数也就没有参数
    INT& operator++()
    {
        ++(this->m_i);
        return *this;
    }
    const INT operator++(int)
    {
        INT temp = this->m_i;
        ++(*this);
        return temp;
    }


    INT& operator--()
    {
        --(this->m_i);
        return *this;
    }
    const INT operator--(int)
    {
        INT temp = this->m_i;
        --(*this);
        return temp;
    }


    //dereference
    int& operator*() const
    {
       return (int&)m_i;
    }


friend ostream& operator<<(ostream& os,const INT& i);
};


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


int main()
{
    INT I(5);
    cout << I;
    cout << I++;
    cout << ++I;
    cout << I--;
    cout << --I;
    cout << *I;


    cout << endl;
    return 0;

前置和后置自增以及解引用重载函数(++、--、*)

标签:

原文地址:http://blog.csdn.net/u011487593/article/details/45339233

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!