题解 | #加号运算符重载#
加号运算符重载
https://www.nowcoder.com/practice/b9e27fcf61fc4013875409ed78e0960b
这道题不需要对time.minutes进行取模运算,因为题目已经说了,minutes < 59 ,所以两个时间相加最大不会超过128,也就是说minutes最多减60,hours最多加1。
#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+(Time &t1, Time &t2) { Time time; time.hours = t1.hours + t2.hours; time.minutes = t1.minutes + t2.minutes; if(time.minutes >= 60) { time.minutes -= 60; time.hours += 1; } return time; } 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; }