自己用C++补写的电子钟,感动!!!!喜欢自己!!!
设计一款电子钟类,用于显示时、分、秒
1. 含有形参有默认值的默认构造函数;
2. 重载 前缀++ 和 后缀—用于调整时间,每次调整均对秒进行调整,若秒满60,则分加1,若分满60则时加1,时满24,则清零重新开始;
3. 重载插入运算符 >> 用于输入(设定)时间;
4. 重载插入运算符 << 用于输出时间。
#pragmaonce #include<windows.h>// #include<iostream> usingnamespacestd; classtime { inthour; intminute; intsecond; public: friendistream&operator>>(istream&,time&); friendostream&operator<<(ostream&,time&); //friend int operator==(time&, time&); voidoperator++(); voidoperator--(); time(void); ~time(void); }; #include"time.h" time::time(void):hour(0),minute(0),second(0){} istream&operator>>(istream&input,time&a) { input>>a.hour>>a.minute>>a.second; returninput; } ostream&operator<<(ostream&output,time&a) { output<<a.hour<<":"<<a.minute<<":"<<a.second<<endl; returnoutput; } voidtime::operator++() { second++; if(second>=60) {minute++; second=0;} if(minute>=60) {hour++; minute=0; hour%=24; //当hour=12时:hour%=24;的结果还是12; //当hour=24时:hour%=24;的结果是0; //当hour=25时:hour%=24;的结果是1; //这个能保证:时满24,则清零重新开始 //记住这种算法就行了,这个老师没讲过,但是很好用 } } voidtime::operator--() { second--; if(second<=0) {minute--;second=59;} if(minute<0) {minute=59;hour--;} if(hour<0) hour=23; } //普通等价函数 /*int operator==(time&a,time&b) { bool found; if(a.hour == b.hour&& a.minute == b.minute&& a.second == b.second) bool found=true; else bool found=false; return found; }*/ time::~time(void){} #include"time.h" intmain() { cout<<"选择功能:"<<endl<<"钟表功能输入1;"<<'\t'<<"正计时功能输入2;"<<'\t'<<"正计时功能输入3;"<<endl; inti; cin>>i; while(i==1) { cout<<"请先校准时间:"<<endl; timea; cin>>a; for(;;a++) { system("cls");//清屏操作 //先对秒加,在对分钟、小时加 cout<<a; Sleep(1000);//间隔为1秒 } } while(i==2) { timea; cout<<"正计时功能:"<<endl; for(;;a++) { system("cls");//清屏操作 //a++;//先对秒加,在对分钟、小时加 cout<<a; Sleep(1000);//间隔为1秒 } } while(i==3) { cout<<"倒计时功能:"; timea; timeb; cout<<"请输入时间:"; cin>>a; for(;;a--) { system("cls"); cout<<a;//运算符对应的数据也是受限制的;不太灵活 //cout<<a--;无法实现 Sleep(1000);//间隔为1秒 /* if(a==b) { cout << "STOP!" << endl; return 0; }*/ } } return0; }