通过对C++运算符重载,实现两个时间的相加

#include <iostream>

using std::string;
using std::cout;
using std::endl;

class Time
{
    

public:
    int hours;
    int minutes;
    int seconds;
    Time(int h, int m, int s) 
    : hours(h), minutes(m), seconds(s) 
    {
        cout << hours << ":" << minutes << ":" << seconds << endl;
    }

    //类内重载运算符
    Time operator+(const Time& t)
    {
        cout << "类内重载 + operator" << endl;
        int newHours = this->hours + t.hours;
        int newMinutes = this->minutes + t.minutes;
        int newSeconds = this->seconds + t.seconds;

        if (newSeconds >= 60)
        {
            newMinutes += newSeconds / 60;
            newSeconds %= 60;
        }

        if (newMinutes >= 60)
        {
            newHours += newMinutes / 60;
            newMinutes %= 60;
        }

        if (newHours >= 24)
        {
            newHours %= 24;
        }

        return Time(newHours, newMinutes, newSeconds);
    }

    // 类内重载 << operator
    //此处的firend关键字是必须的,因为cout不是Time的成员函数
    //在C++中,<< 运算符通常用于输出流,为了使用<<运算符输出Time对象,需要重载<<运算符
    friend std::ostream &operator<<(std::ostream &os,const Time &t)
    {
        os << t.hours << ":" << t.minutes << ":" << t.seconds << endl;
        return os;
    }

    ~Time()
    {
        cout << "时间的析构函数" << endl;
    }
};

// 类外重载 + operator
Time operator+( Time& t1,  Time& t2)
{
    cout << "类外重载 + operator" << endl;
    int newHours = t1.hours + t2.hours;
    int newMinutes = t1.minutes + t2.minutes;
    int newSeconds = t1.seconds + t2.seconds;

    if (newSeconds >= 60)
    {
        newMinutes += newSeconds / 60;
        newSeconds %= 60;
    }

    if (newMinutes >= 60)
    {
        newHours += newMinutes / 60;
        newMinutes %= 60;
    }

    if (newHours >= 24)
    {
        newHours %= 24;
    }

    return Time(newHours, newMinutes, newSeconds);
}

int main(int argc, char const *argv[])
{
    Time t1(11,50,25);
    Time t2(2,30,45);

    //Time t3 = t1 + t2; // 类外重载
    Time t3 = t1.operator+(t2); // 类内重载
    cout << "--------" << endl;
    cout << t3 ; //通过类内重载 << operator 输出
    return 0;
}

在C++中,friend关键字用于声明一个友元函数或友元类。友元函数或友元类可以访问类的私有成员和保护成员,即使它们不是类的成员函数或成员类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值