在C++中自增运算符分为前置++和后置++。前置++是先进行+1操作,然后返回+1之后的值;后置++是先返回值,然后再进行+1操作。
仿照《STL源码剖析》,写的自增操作。
#include<iostream>
using namespace std;
class My{
private:
int m_i;
public:
friend ostream& operator<<(ostream& os,const My& my);
My(int i):m_i(i){};
My& operator++(){
++(this->m_i);
return *this;
}
const My operator++(int){
My temp = *this;
++(*this);
return temp;
}
};
ostream& operator<<(ostream& os,const My& my){
os<<'['<<my.m_i<<']'<<endl;
return os;
}
前置++和后置++需要进行运算符重载,貌似按照规定对