c++编程,仿照课后的Date类,设计Time类,实现构造函数的重载,包括无参的(默认时间为0,0,0),含二个参数的(默认的秒值为0),含一个参数的(默认的分,秒值为0),含三个参数的。4个时间对象分别为(0 0 0),(10,0,0),(10,20,0),(10,40,30),输出时间,以及进行时间的加减运算。
时间: 2024-02-09 11:13:20 浏览: 57
c++ 入门 构造函数 时间类
4星 · 用户满意度95%
好的,以下是Time类的实现代码:
```c++
#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 = 0, int s = 0) : hour(h), minute(m), second(s) {} // 含一个、两个或三个参数的构造函数
void printTime() { // 输出时间
cout << hour << ":" << minute << ":" << second << endl;
}
Time operator+ (const Time& t) { // 重载加法运算符
int h = hour + t.hour;
int m = minute + t.minute;
int s = second + t.second;
if (s >= 60) {
s -= 60;
m++;
}
if (m >= 60) {
m -= 60;
h++;
}
return Time(h, m, s);
}
Time operator- (const Time& t) { // 重载减法运算符
int h = hour - t.hour;
int m = minute - t.minute;
int s = second - t.second;
if (s < 0) {
s += 60;
m--;
}
if (m < 0) {
m += 60;
h--;
}
return Time(h, m, s);
}
};
int main() {
Time t1;
Time t2(10);
Time t3(10, 20);
Time t4(10, 40, 30);
cout << "t1: ";
t1.printTime();
cout << "t2: ";
t2.printTime();
cout << "t3: ";
t3.printTime();
cout << "t4: ";
t4.printTime();
Time t5 = t2 + t3;
Time t6 = t4 - t2;
cout << "t2 + t3 = ";
t5.printTime();
cout << "t4 - t2 = ";
t6.printTime();
return 0;
}
```
输出结果:
```
t1: 0:0:0
t2: 10:0:0
t3: 10:20:0
t4: 10:40:30
t2 + t3 = 20:20:0
t4 - t2 = 0:40:30
```
阅读全文