clock_member自增自减重载实现

/*代码如下*/

 1 #ifndef CLOCK_H
 2 #define CLOCK_H
 3 
 4 class Clock {
 5     public:
 6         Clock(int h=0,int m=0, int s=0);
 7         Clock& operator++();  // 前置++,形如++t
 8         Clock operator++(int notused);  // 后置++,形如t++
 9         Clock& operator--();
10         Clock operator--(int notused);
11         void showTime();
12     private:
13         int hour,minute, second;
14 };
15 
16 #endif
clock.h
 1 #include "clock.h"
 2 #include <iostream>
 3 #include <cstdlib> 
 4 #include <iomanip>
 5 using namespace std;
 6         
 7 const int HT = 24;        
 8         
 9 Clock::Clock(int h,int m, int s):hour(h), minute(m), second(s) {
10     
11     if(! (hour >= 0 && hour < HT && minute >= 0 && minute < 60 && second >=0 && second < 60 ) ) {
12         cout << "时钟值不在合理范围..." << endl;
13         exit(0); 
14     }
15              
16 }
17 
18 // ++t 
19 Clock& Clock::operator++(){
20     ++second;
21     
22     minute += (second / 60);
23     second %= 60;
24     
25     hour += (minute / 60);
26     minute %= 60;
27     
28     hour %= HT;
29     
30     return *this;
31 } 
32 
33 // t++
34 Clock Clock::operator++(int notused){
35     Clock old = *this;
36     
37     ++(*this);
38     
39     return old;
40 }
41 
42 
43 void Clock::showTime() {
44     cout << setw(2) << setfill('0') << hour   <<":" 
45          << setw(2) << setfill('0') << minute << ":" 
46          << setw(2) << setfill('0') << second << endl;
47 }
48 
49 Clock& Clock::operator--() {
50     if (second == 0) {
51         second = 59;
52         if (minute == 0) {
53             minute = 59;
54             if (hour == 0)
55                 hour = HT - 1;
56         }
57     }
58     else
59         second--;
60     return *this;
61 }
62 Clock Clock::operator--(int notused) {
63     Clock old;
64     old = *this;
65      --(*this);
66      return old;
67 }
clock.cpp
 1 #include "clock.h"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 int main() {
 6     cout << "自减重载:" << endl;
 7     Clock t1(0,0,0), t2(t1), t3, t4;
 8     
 9     t3 = t1--;
10     t4 = --t2;
11     
12     t1.showTime();system("pause");
13 
14     t2.showTime();system("pause");
15 
16     t3.showTime();system("pause");
17 
18     t4.showTime();system("pause");
19 
20     cout << "自增重载:" << endl;
21 
22     Clock c1(23,59,59), c2(c1), c3, c4;
23     
24     c3 = c1++;
25     c4 = ++c2;
26     
27     c1.showTime();system("pause");
28 
29     c2.showTime();system("pause");
30 
31     c3.showTime();system("pause");
32 
33     c4.showTime();system("pause");
34     
35     return 0;
36 }
main.cpp

/*运行截图*/

临界情况的测试。

 

posted @ 2019-05-10 09:04  爱因斯坦PLUS  阅读(234)  评论(0编辑  收藏  举报