STL源码剖析之重载操作符

来源:互联网 发布:图灵机原理 知乎 编辑:程序博客网 时间:2024/06/05 19:44
#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;}

0 0