您的位置:首页 > 其它

4-2 电子时钟中的运算符重载

2016-10-20 15:53 197 查看
4-2 电子时钟中的运算符重载

#include<iostream>
#include<cstring>
using namespace std;
int a,b,c;
class Time
{
public :
Time (){hour=0;minute=0;sec=0;}
Time(int a,int b,int c):hour(a),minute(b),sec(c){}
Time operator ++();
friend void putin(Time &t);
friend  bool operator==( Time &a, Time &b) ;
friend int getsum(Time &a) ;
friend  bool operator >( Time &a, Time &b) ;
void display();
private:
int hour;
int minute;
int sec;
};
bool operator==( Time &a, Time &b)
{
if(a.hour==b.hour&&a.minute==b.minute&&a.sec==b.sec)return 1;
return 0;
}
int getsum(Time &a)
{
return a.hour*3600+a.minute*60+a.sec;
}
bool operator >( Time &a, Time &b)
{
if(getsum(a)>getsum(b))return 1;
return 0;
}
void putin(Time &t)
{
cin>>t.hour>>t.minute>>t.sec;
if(t.hour<0||t.hour>12)t.hour=12;
if(t.sec<0||t.sec>59)t.sec=0;
if(t.minute<0||t.minute>59)t.minute=0;
}
Time Time::operator++()
{
if(++sec>=60)
{
sec-=60;

if(++minute>=60)
{
minute-=60;
++hour;
}
}
return *this;
}
void Time::display()
{
if(hour<10)
cout<<"0"<<hour<<":";
else
cout<<hour<<":";
if(minute<10)
cout<<"0"<<minute<<":";
else
cout<<minute<<":";
if(sec<10)
cout<<"0"<<sec;
else
cout<<sec;
cout<<endl;
}
int main()
{
Time t1,t2;
putin(t1);
putin(t2);
if(t1>t2)
cout<<"The begin time is not earlier than the end time!"<<endl;
else
{
while(!(t1>t2))
{
t1.display();
++t1;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class