C++ 前置和后置

#include <iostream>

// 重载前置和后置操作符
class UInt{
public:
    UInt():m_id(0) {}
    friend std::ostream& operator<<(std::ostream& cout, const UInt &it);
    // 前置自增
    UInt& operator++() {
        std::cout<<"prefix++"<<std::endl;
        (*this) +=1;
        return *this;
    }
    // 后置自增,为了区分前置自增,参数中需要有int类型参数(函数体中并不用到,实参都是0)
    // 需要申请变量保留旧的值
    const UInt operator++(int i) {
        std::cout<<"postfix++"<<std::endl;
        UInt old = *this;
        ++(*this);
        return old;// 函数返回const原因是,不支持it++++操作,即便支持,后面++也是对it++的对象进行加1,而不是it加1
    }

    UInt& operator+=(int i) {
        std::cout<<"+="<<std::endl;
        (*this).m_id +=i;
        return *this;
    }
    
    int m_id;
};

std::ostream& operator<<(std::ostream& cout, const UInt &it){
        std::cout<<it.m_id<<std::endl;
        return cout;
}

void Test()
{
    UInt it;
    it++;
    std::cout<<it<<std::endl;
    UInt it1;
    ++(++it1);
    std::cout<<it1<<std::endl;
}
int main()
{
    Test();

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值