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

< 上一页C++重载[] C++重载new和delete下一页 >
自增++和自减--都是一元运算符,它的前置形式和后置形式都可以被重载。请看下面的例子:
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. //秒表类
  6. class stopwatch{
  7. public:
  8. stopwatch(): m_min(0), m_sec(0){ }
  9. public:
  10. void setzero(){ m_min = 0; m_sec = 0; }
  11. stopwatch run(); // 运行
  12. stopwatch operator++(); //++i,前置形式
  13. stopwatch operator++(int); //i++,后置形式
  14. friend ostream & operator<<( ostream &, const stopwatch &);
  15. private:
  16. int m_min; //分钟
  17. int m_sec; //秒钟
  18. };
  19.  
  20. stopwatch stopwatch::run(){
  21. ++m_sec;
  22. if(m_sec == 60){
  23. m_min++;
  24. m_sec = 0;
  25. }
  26. return *this;
  27. }
  28.  
  29. stopwatch stopwatch::operator++(){
  30. return run();
  31. }
  32.  
  33. stopwatch stopwatch::operator++(int n){
  34. stopwatch s = *this;
  35. run();
  36. return s;
  37. }
  38.  
  39. ostream &operator<<( ostream & out, const stopwatch & s){
  40. out<<setfill('0')<<setw(2)<<s.m_min<<":"<<setw(2)<<s.m_sec;
  41. return out;
  42. }
  43.  
  44. int main(){
  45. stopwatch s1, s2;
  46.  
  47. s1 = s2++;
  48. cout << "s1: "<< s1 <<endl;
  49. cout << "s2: "<< s2 <<endl;
  50. s1.setzero();
  51. s2.setzero();
  52.  
  53. s1 = ++s2;
  54. cout << "s1: "<< s1 <<endl;
  55. cout << "s2: "<< s2 <<endl;
  56. return 0;
  57. }
运行结果:
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() 函数,之后再将先前保存的对象返回。在这个函数中参数n是没有任何意义的,它的存在只是为了区分是前置形式还是后置形式。

自减运算符的重载与上面类似,这里不再赘述。
< 上一页C++重载[] C++重载new和delete下一页 >