您的位置:首页 > 其它

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

2016-12-10 20:10 393 查看
题目链接:点击打开链接

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

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

通过本题目的练习可以运算符重载的方法;

设计一个时间类Time,私有数据成员有hour(时)、minute(分)、second(秒);

公有成员函数有:setHour(int)设置数据成员hour的值,非法的输入默认为12;setMinue(int)设置数据成员minute的值,非法输入默认为0;setSecond(int)设置数据成员second的值,非法输入默认为0;setTime(int,int,int)设置时、分、秒三个数据成员的值;三个成员函数int getHour(); int getMinute(); int getSecond();分别用于获取时间对象的属性值。

定义两个构造函数Time(); 和 Time(int,int,int);

定义一个成员函数void displayTime(); 用于显示时间,注意格式为 hh:mm:ss,位数不够用0填充;

定义一个时钟增加1的成员函数 void tick(); 把second的值加1,并注意是否到60;

定义一个成员或友元函数 bool operator= =(….); 判断两个时间对象的值是否相等;

定义一个成员或友元函数bool operator>(…..); 判断第一个时间对象的值是否大于第二个时间对象的值。

在主函数main()中指定开始时间和结束时间,并调用相应成员函数,显示从开始时间到结束时间之间所有时间对象的值,其格式见示例输出。

Input

输入6个整数,之间用一个空格间隔;分别表示开始时间的时、分、秒和结束时间的时、分、秒的值

Output

从开始时间到结束时间之间所有时间对象的值;每个值占一行,格式为hh:mm:ss

Example Input

01 01 01 01 01 10

Example Output

01:01:01

01:01:02

01:01:03

01:01:04

01:01:05

01:01:06

01:01:07

01:01:08

01:01:09

01:01:10

Hint

输入

11 10 12 10 12 56

输出

The begin time is not earlier than the end time!

代码实现:

#include <iostream>
#include <iomanip>
using namespace std;

class Time
{
private:
int hour;
int minute;
int second;
public:
Time(){hour = 12;minute = 0;second = 0;}
Time(int h,int m,int s):hour(h),minute(m),second(s){}

void setHour(int h)
{
if(h >= 0&&h <= 12)
hour = h;
else
hour = 12;
}
void setMinue(int m)
{
if(m >= 0&&m <= 59)
minute = m;
else
minute = 12;
}
void setSecond(int s)
{
if(s >= 0&&s <= 59)
second = s;
else
second = 0;
}
void setTime(int h,int m,int s)
{
if(h >= 0&&h <= 12)
hour = h;
else
hour = 12;
if(m >= 0&&m <= 59)
minute = h;
else
minute = 12;
if(s >= 0&&s <= 59)
second = s;
else
second = 0;
}
int getHour(){return hour;}
int getMinute(){return minute;}
int getSecond(){return second;}
void displayTime()
{
cout<<setw(2)<<setfill('0')<<hour;
cout<<":"<<setfill('0')<<setw(2)<<minute;
cout<<":"<<setfill('0')<<setw(2)<<second<<endl;
}
void tick()
{
if(++second == 60)
{
minute++;
second = 0;
if(minute == 60)
{
hour++;
minute = 0;
if(hour == 12)
hour = 0;
}
}
}
int operator==(const Time &a)
{
if(a.hour == hour && a.minute == minute && a.second == second)
return 1;
else
return 0;
}
int getsum()
{
return hour*3600+minute*60+second;
}
int operator>(Time &a)
{
if(getsum() > a.getsum())
return 1;
else
return 0;
}
};

int main()
{
int h,m,s;
cin>>h>>m>>s;
Time T1(h,m,s);
cin>>h>>m>>s;
Time T2(h,m,s);
if(T1 > T2)
cout<<"The begin time is not earlier than the end time!"<<endl;
else
{
while(!(T1 > T2))
{
T1.displayTime();
T1.tick();
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: