|
本帖最后由 daming 于 2014-12-30 02:15 編輯
- #include<iostream>
- using namespace std;
- class Clock //時鐘類定義
- {
- public: //外部接口
- Clock(int H=0,int M=0,int S=0);
- void show_time();
- Clock& operator ++(); //前置單目運(yùn)算符重載
- Clock operator ++(int); //后置單目運(yùn)算符重載
- private: //私有數(shù)據(jù)成員
- int Hour,Minute,Second;
- };
- Clock::Clock(int H,int M,int S) //構(gòu)造函數(shù)
- {
- if((H >=0&&H <=23)&&(M >=0&&M <=59)&&(S >=0&&S <=59))
- {
- Hour=H;
- Minute=M;
- Second=S;
- }
- else
- cout<<"Time error!"<<endl;
- }
- void Clock::show_time() //顯示時間函數(shù)
- {
- cout<<Hour<<":"<<Minute<<":"<<Second<<endl;
- }
- Clock& Clock::operator ++() //前置單目運(yùn)算符重載函數(shù)
- {
- Second++;
- if(Second>=60){
- Second=Second-60;
- Minute++;
- if(Minute>=60){
- Minute=Minute-60;
- Hour++;
- Hour=Hour%24;
- }
- }
- return *this;
- }
- Clock Clock::operator ++(int) //后置單目運(yùn)算符重載, 注意形參表中的整型參數(shù)
- {
- Clock old=*this;
- ++(*this);
- return old;
- }
- int main()
- {
- Clock A(23,59,59);
- cout<<"First time output:";
- A.show_time();
- cout<<"Show A++:";
- (A++).show_time();
- cout<<"show ++A:";
- (++A).show_time();
- }
復(fù)制代碼
|
|