#include<iostream>
using namespace std;
class INT{
public:
INT(int i):m_i(i){};
friend ostream& operator<<(ostream& os,const INT& i);
int& operator*()const//重载解除指针操作符
{
return (int&)m_i;
}
const INT operator++(int)//不能写成const &INT operator++(),因为不能引用零时变量
{
INT temp=*this;
++(*this);
return temp;
}
INT& operator++()
{
++(this->m_i);//写成这样会递归爆栈,++(*this)
return *this;
}
const INT operator--(int)//不能写成const &INT operator--(),因为不能引用零时变量
{
INT temp=*this;
--(*this);
return temp;
}
INT& operator--()
{
--(this->m_i);//写成这样会递归爆栈,--(*this)
return *this;
}
private:
int m_i;
};
ostream& operator<<(ostream& os,const INT& i)
{
cout<<i.m_i<<endl;
return os;
}
int main()
{
INT i(5);
cout<<++i;
cout<<i++;
cout<<i--;
cout<<--i;
return 0;
}
STL源码剖析之重载操作符
最新推荐文章于 2024-09-20 17:52:21 发布