首页 C/C++
时钟
发布时间:2017年06月30日 评论数:抢沙发 阅读数:306
-
#include<iostream>
using namespace std;
class Time{
private:
int h,m,s;
public:
Time(){//少了无参构造函数,这样下面的Time t2,t3因为找不到对应构造函数而报错
}
Time(int t_h,int t_m,int t_s){
h=t_h;
m=t_m;
s=t_s;
}
void ShowTime(){
cout<<this<<endl;
}
Time& operator++(){//前置++
if(s<59)
s++;
else if(m<59){
s=0;
m++;
}else if(h<24){
s=0;
m=0;
h++;
}else{
s=0;
m=0;
h=0;
}
return *this;
}
Time& operator--(int){//后置--
if(s>0)//59-1中间两秒间隔
s--;
else if(m>0){
s=59;
m--;
}else if(h>0){
s=59;
m=59;
h--;
}else{
s=59;
m=59;
h=23;
}
return *this;
}
friend ostream &operator<<(ostream &os,Time &a){
return os<<"Time:"<<a.h<<"-"<<a.m<<"-"<<a.s<<endl;
}
friend istream &operator>>(istream &is,Time &a){
return is>>a.h>>a.m>>a.s;
}
};
int main(){
Time t1(12,2,3);//初始化一个时钟对象
Time t2,t3;//定义两个维初始化的时钟对象
cin>>t2>>t3;//对t2 t3开始进行赋值(也就是设置时间)
++t2;
t3--;
//通过重载的输出流对时钟进行显示
cout<<"t1->"<<t1<<endl;
cout<<"t2->"<<t2<<endl;
cout<<"t3->"<<t3<<endl;
return 0;
}
相关文章