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

本文介绍了一个使用C++实现的电子时钟程序,该程序通过重载运算符来实现时间的递增和比较功能。具体实现了Time类,并在其中定义了前置递增运算符、等于运算符和大于运算符。

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值