题解 | #加号运算符重载#

加号运算符重载

http://www.nowcoder.com/practice/b9e27fcf61fc4013875409ed78e0960b

运算符重载,函数:return type operator + 运算符

  • 作为类成员函数重载:Time operator + (Time t)
  • 非类成员函数 Time operator+ (Time t1, Time t2)
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 t2)
        {
            int hour = this->hours + t2.hours;
            int minute = this->minutes + t2.minutes;
            hour += minute / 60;
            minute %= 60;
            return Time(hour, minute);
        }
        

};
// Time operator+ (Time t1, Time t2)  //非成员函数
// {
//     int hour = t1.hours + t2.hours;
//     int minute = t1.minutes + t2.minutes;
//     hour += minute / 60;
//     minute %= 60;
//     return Time(hour, minute);
// }

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;
}
全部评论

相关推荐

Java抽象带篮子:难蚌,点进图片上面就是我的大头😆
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务