ITeye博客

重载运算符之前++和后++

gowithbutton · 2011-12-21 10:19 · java · 重载运算符之前++和后++ · Markdown

下面例子程序中 const Fraction operator ++(int) 中 int不过是个哑元(dummy),是永远用不上的 它只是用来判断++是prefix 还是 postfix 记住,如果有哑元,则是postfix,否则,就是prefix 就像其他的一元算法和逻辑运算一样 而其实在C++中用到这种哑元的也只有在postfix ++ 和--了

例子:

int i=10; cout<<i++<<endl;//i=11;后缀加;先返回后自增;10 cout&lt;&lt;++i&lt;&lt;endl;//i=12;前缀加;先自增后返回;12

例:

#include using namespace std;

class Fraction//数类; {friend ostream&amp; operator&lt;&lt;(ostream&amp; out, const Fraction&amp; x); private:int den;//加的步进距离,使自加的距离不是1;int num;//数(初值); public:Fraction(int d=1, int n=0):den(d),num(n) {}Fraction&amp; operator++()//前缀自加重载;(前置版本prefix){num+=den;//先自增,再返回;return *this;}const Fraction operator ++(int)//后缀自加重载;(后置版本postfix){Fraction old (*this);//拷贝构造(对象参数是对象)。先返回,再自增;++(*this);//调用的是重载的前置版本;return old;

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。