请设计时间类TIME,实现时间的输入、输出和比较。
#include <iostream>
#include <iomanip>
using namespace std;
/* 你提交的代码将被嵌在这里 */
int main()
{
TIME a, b;
cin >> a >> b;
if (a > b)
{
cout << "Yes\n";
}
else
{
cout << "No\n";
}
return 0;
}
输入样例
9:0:1
8:59:58
输出样例
Yes
设计要求:
- 设计构造函数,达到以下效果。
测试代码1
TIME a;
cout << a << endl;
输出样例1
00:00:00
测试代码2
TIME a(8);
cout << a << endl;
输出样例2
08:00:00
测试代码3
TIME a(8, 30);
cout << a << endl;
输出样例3
08:30:00
测试代码4
TIME a(8, 30, 45);
cout << a << endl;
输出样例4
08:30:45
- 重载输出运算符函数,达到以下效果。
测试代码1
TIME a(9, 15)
cout << a << endl;
输出样例1
09:15:00
测试代码2
TIME a(8, 50), b(9, 15, 47);
cout << a << ' ' << b << endl;
输出样例2
08:50 09:15:47
- 重载输入运算符函数,达到以下效果。
测试代码1
TIME a;
cin >> a;
cout << a << endl;
输出样例1
8:3:5
08:03:05
测试代码2
TIME a, b;
cin >> a >> b;
cout << a << ' ' << b << endl;
输出样例2
0:0:1 23:0:0
00:00:01 23:00:00
- 重载大于运算符,达到以下效果。
测试代码1
TIME a(9, 0, 1), b(8, 59, 58);
if (a > b)
{
cout << "Yes\n";
}
else
{
cout << "No\n";
}
输出样例1
Yes
测试代码2
TIME a(3, 4, 5), b(2), c, d(1, 59);
if (a > b && c > d)
{
cout << "Yes\n";
}
else
{
cout << "No\n";
}
输出样例2
No
运行代码如下:
class TIME{
private:
int hour;
int minute;
int second;
public:
TIME(int h=0,int m=0,int s=0){
hour=h;minute=m;second=s;
}
friend ostream& operator<<(ostream &os,const TIME &t);
friend istream& operator>>(istream &is,TIME &t);
friend bool operator>(TIME a,TIME b);
};
istream& operator>>(istream &is,TIME& t){
char colon;
is>>t.hour>>colon>>t.minute>>colon>>t.second;
return is;
}
ostream& operator<<(ostream &os,const TIME& t){
os<<setfill('0')<<setw(2)<<t.hour<<":"<<setw(2)<<t.minute<<":"<<setw(2)<<t.second;
return os;
}
bool operator>(TIME a,TIME b){
if(a.hour>b.hour){
return true;
}
else{
if(a.hour==b.hour)
{
if(a.minute>b.minute)
{
return true;
}else
{
if(a.minute==b.minute)
{
if(a.second>b.second)
{
return true;
}else{
return false;
}
}else{
return false;
}
}
}else
{
return false;
}
}
}
思路:这个代码定义了一个名为TIME的类,包含了四个构造函数、两个重载运算符函数和一个比较运算符函数。其中,构造函数用于初始化时间对象,重载输出运算符函数用于将时间对象以特定格式输出到输出流中,重载输入运算符函数用于从输入流中读取时间对象的数据,比较运算符函数用于比较两个时间对象的大小。在主函数中,通过输入运算符>>读入两个时间对象a和b,然后通过比较运算符>判断a是否大于b,最后输出结果。
这段代码使用了std::istream,这是C++标准库中的输入流类,用于从输入流(如键盘输入)中读取数据。
在这段代码中,operator>>被重载用于从输入流中读取时间数据。通过使std::istream& operator>>(std::istream& is, TIME& c),我们可以从输入流中读取TIME对象的hours、minutes和seconds成员变量。在函数实现中,输入流首先读取小时(c.hours),然后读取一个冒号(:),接着读取分钟(c.minutes),最后再读取一个冒号,最后读取秒(c.seconds)。通过这种方式,输入流可以按照指定的格式读取时间数据。
使用输入流类std::istream的好处是,它提供了一种方便的方式来从各种输入源(如键盘、文件等)中读取数据,并将其存储到程序中的变量中。此外,通过重载operator>>,我们可以自定义数据读取的方式和格式,以满足特定的需求。
总结起来,使用std::istream是为了从输入流中读取时间数据,并通过重载operator>>来定义自定义的读取方式和格式。