各位大侠帮帮忙吧 这道题用C++怎么做?

编写一个时间类,利用重载运算符实现时间对象的加、减运算并输出。... 编写一个时间类,利用重载运算符实现时间对象的加、减运算并输出。 展开
 我来答
牛顿一餐一顿牛
2012-04-08 · TA获得超过638个赞
知道小有建树答主
回答量:287
采纳率:0%
帮助的人:218万
展开全部
#include <iostream>
using namespace std;

class Time
{
private:
int hour;
int minute;
int second;
public:
Time()
{
hour = 0;
minute = 0;
second = 0;
}
Time(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
}
friend Time operator + (Time &t1, Time &t2);
friend Time operator - (Time &t1, Time &t2);
void display();
};

void Time::display()
{
cout << hour << ":" << minute << ":" << second << endl;
}

Time operator + (Time &t1, Time &t2)
{
Time t;
t.second = (t1.second + t2.second) % 60;
t.minute = (t1.minute + t2.minute + (t1.second + t2.second) / 60) % 60;
t.hour = (t1.hour + t2.hour + (t1.minute + t2.minute + (t1.second + t2.second) / 60) / 60) % 24;
return t;
}

Time operator - (Time &t1, Time &t2)
{
Time t;
t.second = (t1.second - t2.second + 60) % 60;
int m = 0;
if(t1.second < t2.second)
{
m = 1;
}
t.minute = (t1.minute - t2.minute - m + 60) % 60;
int h = 0;
if(t1.minute < t2.minute)
{
h = 1;
}
t.hour = (t1.hour - t2.hour - h + 24) % 24;
return t;
}

int main()
{
int h1, m1, s1, h2, m2, s2;

cout << "intput h1,m1,s1:" << endl;
cin >> h1 >> m1 >> s1;
cout << "intput h2,m2,s2:" << endl;
cin >> h2 >> m2 >> s2;

Time t1(h1, m1, s1);
Time t2(h2, m2, s2);
Time t = t1 + t2;

cout << "t1: ";
t1.display();
cout << "t2: ";
t2.display();
cout << "t1+t2: ";
t.display();

t = t1 - t2;
cout << "t1-t2: ";
t.display();

return 0;
}
Anycallmotion
2012-04-12 · TA获得超过125个赞
知道答主
回答量:209
采纳率:0%
帮助的人:99.5万
展开全部
书上都有的啊
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式