问题:运算符重载时如何区分prefix和postfix形式?

(注:晚上看书才发现原来这是《More Effective C++》条款M6 果然不看书是不行的...)

  Answer:下面例子程序中   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);                       //调用的是重载的前置版本;
  

相关文章: