++操作符的重载

  1.全局函数和成员函数都可以进行重载。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

  2.前置++操作符不需要参数。

  3.后置++操作符需要int类型的占位参数(区分前置后置)。

 

 

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int mValue;
public:
    Test(int i)
    {
        mValue = i;
    }
    
    int value()
    {
        return mValue;
    }
    
    Test& operator ++ () // 前置++
    {
        ++mValue;
        
        return *this;  // 返回加一后的数
    }
    
    Test operator ++ (int)  // ++后置要带一个参数
    {
        Test ret(mValue);
        
        mValue++;
        
        return ret;  // 返回加一前的数
    }
};

int main()
{
    Test t(0);
    
    t++;
    
    ++t;
    
    return 0;
}

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄