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

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

 例子:

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

例:

#include<iostream>
using namespace std;

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

ostream& operator<<(ostream& out, const Fraction& x)
{
 out<<x.num<<endl;
 return out;
}

int main()
{
 Fraction b(10,10);
 cout<<b++<<endl;
 cout<<++b<<endl;
 return 0;
}

前置版本返回一个引用【Fraction& operator++()】,后置版本返回一个const值【const Fraction operator ++(int)】。

后置版本是利用前置版本来实现的。节约代码,控制代码有余。

前置版本的效率高,因为后置版本需要调用前置版本,所有后置版本效率比前置要低。(++i比i++效率高。)

在后置版本里,人为添加一个参数(int),主要是为了区别前置版本,这个参数不会被使用。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值