题目:
编写一个程序,其中设计一个时间类,用来保存时、分、秒等私有数据成员,通过重载运算符“+”实现两个时间相加。要求将小时限制>=0,分钟[0,59]区间,秒[0,59]区间,输出时、分、秒各保持两个宽度,并用0填充。
用到的文件:
main.cpp:
#include <iostream>
using namespace std;
#include <iomanip>//输出字符宽度setw()需要的头文件
#include "class.h"
int main()
{
Time t1(2, 4, 56);
Time t2(3, 56, 7);
Time t3 = t1 + t2;
cout.fill('0');//如果有输出宽度控制,用'0'来填充不足的长度
t1.show();//输出时间
t2.show();
t3.show();
system("pause");
return 0;
}
class.h:
#pragma once
class Time
{
public:
Time(int h,int m,int s);//初始化私有成员
Time operator+(Time &);//成员重载运算符 --- time类对象相加
void show();
private:
int hours;//小时
int minutes;//分
int seconds;//秒
};
Time::Time(int h = 0, int m = 0, int s = 0)
{
hours = h;
minutes = m;
seconds = s;
}
inline Time Time::operator+(Time &s)
{
Time t;
t.hours = hours + s.hours;
t.minutes = minutes + s.minutes;
t.seconds = seconds + s.seconds;
if (t.seconds >= 60)//将秒进位
{
t.seconds -= 60;
t.minutes++;
}
if (t.minutes >= 60)//将分进位
{
t.minutes -= 60;
t.hours++;
}
return t;
}
inline void Time::show()
{
cout << setw(2) << hours << "时";//setw()为控制输出宽度的函数
cout << setw(2) << minutes << "分";
cout<< setw(2) << seconds << "秒" << endl;
}
运行结果: