声明Time类,有hour(小时)、minute(分钟)两个成员数据; 1)用成员函数按分钟实现Time类的++(自增)。数据成员中hour的范围为0~23,minute的范围为0~59。 2)用友元函数实现Time类的--(自减)运算。 3)用成员函数实现Time类的加法(+)运算。 4)用友元函数实现Time类的减法(-)运算。 5)用成员函数实现赋值运算。 6)主函数里定义若干Time类对象,验证以上函数,输出运算结果。
时间: 2024-02-05 22:12:34 浏览: 39
下面是实现Time类的代码示例:
```cpp
#include <iostream>
using namespace std;
class Time {
private:
int hour;
int minute;
public:
Time(int h = 0, int m = 0) : hour(h), minute(m) {}
Time operator++(); // 前置自增
Time operator+(const Time& t) const; // 加法运算
Time& operator=(const Time& t); // 赋值运算
int getHour() const { return hour; }
int getMinute() const { return minute; }
friend Time operator--(Time& t); // 友元函数,前置自减
friend Time operator-(const Time& t1, const Time& t2); // 友元函数,减法运算
};
Time Time::operator++() {
if (++minute >= 60) {
minute = 0;
if (++hour >= 24)
hour = 0;
}
return *this;
}
Time Time::operator+(const Time& t) const {
int h = hour + t.hour;
int m = minute + t.minute;
if (m >= 60) {
h++;
m -= 60;
}
if (h >= 24)
h -= 24;
return Time(h, m);
}
Time& Time::operator=(const Time& t) {
hour = t.hour;
minute = t.minute;
return *this;
}
Time operator--(Time& t) {
if (--t.minute < 0) {
t.minute += 60;
if (--t.hour < 0)
t.hour += 24;
}
return t;
}
Time operator-(const Time& t1, const Time& t2) {
int h = t1.hour - t2.hour;
int m = t1.minute - t2.minute;
if (m < 0) {
h--;
m += 60;
}
if (h < 0)
h += 24;
return Time(h, m);
}
int main() {
Time t1(10, 30), t2(23, 45), t3;
// 前置自增
++t1;
cout << "t1 after ++: " << t1.getHour() << ":" << t1.getMinute() << endl;
// 前置自减
--t2;
cout << "t2 after --: " << t2.getHour() << ":" << t2.getMinute() << endl;
// 加法运算
t3 = t1 + t2;
cout << "t1 + t2 = " << t3.getHour() << ":" << t3.getMinute() << endl;
// 减法运算
t3 = t1 - t2;
cout << "t1 - t2 = " << t3.getHour() << ":" << t3.getMinute() << endl;
// 赋值运算
t3 = t2;
cout << "t3 after assignment: " << t3.getHour() << ":" << t3.getMinute() << endl;
return 0;
}
```
输出:
```
t1 after ++: 10:31
t2 after --: 23:44
t1 + t2 = 10:15
t1 - t2 = 11:46
t3 after assignment: 23:44
```