前置操作符 后置操作符

++操作符的重载

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

  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;
}

 

posted @ 2019-05-09 18:53  张不源  Views(187)  Comments(0)    收藏  举报