4-2 电子时钟中的运算符重载
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
通过本题目的练习可以运算符重载的方法;
设计一个时间类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()中指定开始时间和结束时间,并调用相应成员函数,显示从开始时间到结束时间之间所有时间对象的值,其格式见示例输出。
输入
输入6个整数,之间用一个空格间隔;分别表示开始时间的时、分、秒和结束时间的时、分、秒的值
输出
从开始时间到结束时间之间所有时间对象的值;每个值占一行,格式为hh:mm:ss
示例输入
01 01 01 01 01 10
示例输出
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
#include <iostream>
using namespace std;
class time
{
private:
int h,m,s;
public:
time(int hour=0,int minute=0,int second=0)//构造函数(赋值并处理非法输入)
{
cin>>hour>>minute>>second;
if(hour>12||hour<0)
hour=12;
if(minute>60||minute<0)
minute=0;
if(second>60||second<0)
second=0;
h=hour;
m=minute;
s=second;
}
bool operator != (time &c)//成员函数重载“!=”号
{
if(c.h!=h||c.m!=m||c.s!=s)
return true;
else
return false;
}
bool operator > (time &c)
{
if(h>c.h)
return true;
else if(h==c.h)
{
if(m>c.m)
return true;
else if(m==c.m)
{
if(s>c.s)
return true;
else
return false;
}
else
return false;
}
else
return false;
}
time operator++()
{
if(++s>=60)
{
s-=60;
if(++m>=60)
{
m-=60;
++h;
}
}
return *this;
}
void show()
{
if(h<10)
cout<<"0"<<h<<":";
else
cout<<h<<":";
if(m<10)
cout<<"0"<<m<<":";
else
cout<<m<<":";
if(s<10)
cout<<"0"<<s<<endl;
else
cout<<s<<endl;
}
};
int main()
{
class time c1,c2;
if(c1>c2)
cout<<"The begin time is not earlier than the end time!"<<endl;
else
{
c1.show();
while(c1!=c2)
{
++c1;
c1.show();
}
}
return 0;
}
#include <iostream>
using namespace std;
class time
{
private:
int h,m,s;
public:
time(int hour=0,int minute=0,int second=0)//构造函数(赋值并处理非法输入)
{
cin>>hour>>minute>>second;
if(hour>12||hour<0)
hour=12;
if(minute>60||minute<0)
minute=0;
if(second>60||second<0)
second=0;
h=hour;
m=minute;
s=second;
}
bool operator != (time &c)//成员函数重载“!=”号
{
if(c.h!=h||c.m!=m||c.s!=s)
return true;
else
return false;
}
bool operator > (time &c)
{
if(h>c.h)
return true;
else if(h==c.h)
{
if(m>c.m)
return true;
else if(m==c.m)
{
if(s>c.s)
return true;
else
return false;
}
else
return false;
}
else
return false;
}
time operator++()
{
if(++s>=60)
{
s-=60;
if(++m>=60)
{
m-=60;
++h;
}
}
return *this;
}
void show()
{
if(h<10)
cout<<"0"<<h<<":";
else
cout<<h<<":";
if(m<10)
cout<<"0"<<m<<":";
else
cout<<m<<":";
if(s<10)
cout<<"0"<<s<<endl;
else
cout<<s<<endl;
}
};
int main()
{
class time c1,c2;
if(c1>c2)
cout<<"The begin time is not earlier than the end time!"<<endl;
else
{
c1.show();
while(c1!=c2)
{
++c1;
c1.show();
}
}
return 0;
}