C++中++运算符的重载

 1     void showTime() const;
 2     Clock& operator ++();
 3     Clock operator ++(int);
 4 private:
 5     int hour,minute,second;
 6 };
 7 Clock::Clock(int hour,int minute,int second){
 8     if(0<=hour&&hour<24&&0<=minute&&minute<60&&0<=second&&second<60)
 9        {
10            this->hour=hour;
11            this->minute=minute;
12            this->second=second;
13        }
14     else
15         cout<<"Time error!"<<endl;
16 }
17 
18 void Clock::showTime() const
19 {
20     cout<<hour<<":"<<minute<<":"<<second<<endl;
21 }
22 
23 Clock& Clock::operator ++()
24 {
25     second++;
26     if(second>=60)
27     {
28         second-=60;
29         minute++;
30         if(minute>=60)
31         {
32             minute-=60;
33             hour=(hour+1)%24;
34         }
35     return *this;
36     }
37 }
38 
39 Clock Clock::operator ++(int)
40 {
41     Clock old=*this;
42     ++(*this);
43     return old;
44 }
45 
46 int main()
47 {
48     Clock myClock(23,59,59);
49     cout<<"First time output:";
50     myClock.showTime();
51     cout<<"Show myClock++:   ";
52     (myClock++).showTime();
53     cout<<"Show ++myClock:   ";
54     (++myClock);
55     myClock.showTime();
56     return 0;
57 }
View Code

 

posted @ 2015-06-18 11:05  docyard  阅读(451)  评论(0编辑  收藏  举报