#include <iostream>
using namespace std;
class Time {
public:
int hours; // 小时
int minutes; // 分钟
Time() {
hours = 0;
minutes = 0;
}
Time(int h, int m) {
this->hours = h;
this->minutes = m;
}
void show() {
cout << hours << " " << minutes << endl;
}
// write your code here......
Time operator+(const Time& x) const {
Time res;
res.hours = this->hours + x.hours;
res.minutes = this->minutes + x.minutes;
if (res.minutes >= 60) {
res.hours++;
res.minutes -= 60;
}
return res;
}
};
int main() {
int h, m;
cin >> h;
cin >> m;
Time t1(h, m);
Time t2(2, 20);
Time t3 = t1 + t2;
t3.show();
return 0;
}
将 operator+ 改为接受一个参数 const Time& y,然后在函数内部进行时间的相加运算,并处理可能出现的进位。同时,为了保证不修改调用对象的状态,我们将 operator+ 声明为 const 成员函数。



京公网安备 11010502036488号