打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
14.7 自增操作符和自减操作符

■  前++ 与 后++
  • 相同: 都使得目标值 + 1
  • 区别: 前++ 表达式使用+1后的值;后++ 表达式使用+1前的值
 ■ 重载
     前++ 返回++后的值:
MyInt& MyInt::operator++()
{
    this->i++;
    return *this;
}
    后++ 返回++前的值:
MyInt MyInt::operator++(int)
{
    const MyInt temp = *this;
    ++(*this);
    return temp;
}

■ 例子


#include <iostream>
 
class MyInt{
    public:
    MyInt(int a):i(a) {   }
 
    MyInt& operator++();            // prefix ++
    MyInt operator++(int);    // postfix ++
 
    friend std::ostream& operator<<(std::ostream&,const MyInt&);
 
    private:
    int i;
};
 
MyInt& MyInt::operator++()
{
    this->i++;
    return *this;
}
 
MyInt MyInt::operator++(int)
{
    const MyInt temp = *this;
    ++(*this);
    return temp;
}
 
std::ostream& operator<<(std::ostream& out,const MyInt& t)
{
    out << t.i ;
    return out;
}
 
int main()
{
     MyInt a(0);
     std::cout << a++ << std::endl; // i = 1,print 0
     std:: cout << ++a << std::endl; // i = 2,print 2
     return 0;
}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
第一章 深入浅出IO流
重载操作符解析
string类实现(C++)
VC6.0中重载操作符函数无法访问类的私有成员
C++运算符重载(2)
C++操作符重载(“+”“输入输出”)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服