题解 | 加号运算符重载

#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......
        bool isInRange(const int a)const 
        {
            return a>=0 && a<60;
        }
        Time operator+(const Time&other) const 
        {
            if(isInRange(this->minutes) && isInRange(other.minutes))
            {
                int totalminutes=this->minutes + other.minutes;
                int carryHours = totalminutes / 60;
                int newminutes=totalminutes%60;
                int newhours=(this->hours + other.hours +carryHours);
                return Time(newhours,newminutes);
            }
            else return Time(0,0);
        }

};

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;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务