//3.设计一个时间类Time,包括时、分、秒等私有数据成员。 //重载“+”和“-”运算符以实现时间的加法和减法运算,并进行测试。
时间: 2024-01-06 13:03:28 浏览: 50
好的,以下是Time类的设计:
```cpp
#include <iostream>
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) {} // 构造函数
Time operator+(const Time& t) const { // 重载加法运算符
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) const { // 重载减法运算符
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);
}
void display() const { // 显示时间
std::cout << hour << ":" << minute << ":" << second << std::endl;
}
};
```
接下来是测试程序:
```cpp
int main() {
Time t1(10, 30, 50);
Time t2(1, 20, 10);
Time t3 = t1 + t2;
t3.display(); // 显示:11:51:0
Time t4 = t1 - t2;
t4.display(); // 显示:9:10:40
return 0;
}
```