STL中重载++,--操作符
#include<iostream>
using namespace std;
class INT
{
friend ostream& operator<<(ostream& os, const INT& i);
public:
INT(int x) :m_i(x) {};
INT& operator++()
{
++(this->m_i);
return *this;
}
INT operator++(int)
{
INT temp = *this;
++(*this);
return temp;
}
INT& operator--()
{
--(this->m_i);
return *this;
}
INT operator--(int)
{
INT temp = *this;
--(*this);
return temp;
}
int& operator*()const
{
return (int&)m_i;
}
private:
int m_i;
};
ostream& operator<<(ostream& os, const INT& i)
{
os << i.m_i;
return os;
}
int main()
{
INT I(5);
cout << I++ << endl;
cout << ++I << endl;
cout << I-- << endl;
cout << --I << endl;
cout << *I<< endl;
}
注意:前置返回引用,后置返回临时变量(不能是引用)