C++重载++和–(自增和自减运算符)详解

自增++和自减--都是一元运算符,它的前置形式和后置形式都可以被重载。请看下面的例子:

  #include <iostream>  #include <iomanip>  using namespace std;    //秒表类  class stopwatch{  public:      stopwatch(): m_min(0), m_sec(0){ }  public:      void setzero(){ m_min = 0; m_sec = 0; }      stopwatch run();  // 运行      stopwatch operator++();  //++i,前置形式      stopwatch operator++(int);  //i++,后置形式      friend ostream & operator<<( ostream &, const stopwatch &);  private:      int m_min;  //分钟      int m_sec;  //秒钟  };    stopwatch stopwatch::run(){      ++m_sec;      if(m_sec == 60){          m_min++;          m_sec = 0;      }      return *this;  }    stopwatch stopwatch::operator++(){      return run();  }    stopwatch stopwatch::operator++(int n){      stopwatch s = *this;      run();      return s;  }    ostream &operator<<( ostream & out, const stopwatch & s){      out<<setfill('0')<<setw(2)<<s.m_min<<":"<<setw(2)<<s.m_sec;      return out;  }    int main(){      stopwatch s1, s2;        s1 = s2++;      cout << "s1: "<< s1 <<endl;      cout << "s2: "<< s2 <<endl;      s1.setzero();      s2.setzero();        s1 = ++s2;      cout << "s1: "<< s1 <<endl;      cout << "s2: "<< s2 <<endl;      return 0;  }

运行结果:
s1: 00:00
s2: 00:01
s1: 00:01
s2: 00:01

上面的代码定义了一个简单的秒表类,m_min 表示分钟,m_sec 表示秒钟,setzero() 函数用于秒表清零,run() 函数是用来描述秒针前进一秒的动作,接下来是三个运算符重载函数。

先来看一下 run() 函数的实现,run() 函数一开始让秒针自增,如果此时自增结果等于60了,则应该进位,分钟加1,秒针置零。

operator++() 函数实现自增的前置形式,直接返回 run() 函数运行结果即可。

operator++ (int n) 函数实现自增的后置形式,返回值是对象本身,但是之后再次使用该对象时,对象自增了,所以在该函数的函数体中,先将对象保存,然后调用一次 run() 函数,之后再将先前保存的对象返回。<span

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论