oj 贵州大学 第四次作业(c++)(运算符重载)第八题

设计一个Time类,有hour、minute、second等私有数据成员。 对该类重载+、-和<<运算符。
+运算符函数要实现Time对象和一个正整数n的相加,n理解为秒数,该运算符函数返回当前时间加n秒之后的Time对象。(加之后的时间可能跨到后一天)
-运算符函数重载的第一个版本要实现Time对象和一个正整数n的相减,n理解为秒数,该运算符函数返回当前时间减n秒之后的Time对象。(减之后的时间可能回到前一天)
-运算符函数重载的第二个版本要实现两个Time对象相减(假设两个时间是同一天之内的),该运算符函数返回两个时间相差的秒数。
<<运算符函数重载的目的是为了直接使用cout来输出时间信息。
main函数已经写好,请根据main函数的内容完成该类的设计:
int main(){
int s;
cin>>s;
Time t1(13,30,20);
t1=t1-s;
cout<<t1;
Time t2(21,10,33);
t2=t2+s;
cout<<t2;
cout<<t1-t2<<endl;
return 0; 
}

输入描述输入一个正整数s

输出描述按样例输出

提示你需要提交除了main函数之外的其他代码。

样例输入 

333

样例输出

13:24:47
21:16:6
-28279
 

#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
#define pi 3.14159265
#include<iostream>
using namespace std;
class Time
{
private:
    int hour, minute, second;
public:
    Time() { hour = 0; minute = 0; second = 0; }
    Time(int hour, int minute, int second)
    {
        this->hour = hour;
        this->minute = minute;
        this->second = second;
    }
    friend ostream& operator<<(ostream& out, Time& t)
    {
        out << t.hour << ":" << t.minute << ":" << t.second << endl;
        return out;
    }
    Time& operator+(const int s)
    {
        second += s;
        if (second >= 60)
        {
            int p = second / 60;
            minute += p;
            second = second % 60;
        }
        if (minute >= 60)
        {
            int g = minute / 60;
            hour += g;
            minute = minute % 60;
        }
        if (hour >= 24)
        {
            hour = hour % 24;
        }
        return *this;
    }
    Time& operator-(const int s)
    {
        int g = hour * 3600 + minute * 60 + second - s;
        if (g >= 0)
        {
            hour = g /3600;
            minute = (g % 3600) / 60;
            second= (g % 3600) % 60;
        }
        if (g < 0)
        {
            g=-g;
            hour = 23 - (g / 3600);
            minute = 59 - ((g % 3600) / 60);
            second = 60 - ((g % 3600) % 60);
        }
        return *this;
    }
    friend int operator-(const Time& t1, const Time& t2)
    {
        int g1 = t1.hour * 3600 + t1.minute * 60 + t1.second;
        int g2 = t2.hour * 3600 + t2.minute * 60+ t2.second;
        return g1 - g2;
    }
};

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值