一个简单的表示时间的类 C++实现

//一个表示时间的Time类 (精确到分钟)
#include <iostream>
using namespace std;
class Time
{
private:
    int hours;
    int minutes;
public:
    Time();
    Time(int h, int m = 0);
    void AddMin(int m);
    void AddHr(int h);
    void Reset(int h = 0, int m = 0);
    int toMin() { return minutes + hours * 60; };
    Time operator+(const Time& t) const;
    Time operator-(Time& t);
    Time operator*(Time &t);
    void Show() const;
    friend ostream& operator<<(ostream& om, const Time& t);
};

Time::Time()
{
    hours = minutes = 0;
}

Time::Time(int h, int m)
{
    if (h < 0)
    {
        cout << "Are you kidding me??" << endl;
        hours = 0;
    }
    else
    {
        hours = h;
    }
    if(m<0)
    {
        cout << "Are you kidding me??"<<endl;
        minutes = 0;
    }
    else
    {
        minutes = m;
    }
    hours += minutes / 60;
    minutes %= 60;
}

void Time::AddMin(int m)
{
    minutes += m;
    hours += minutes / 60;
    minutes %= 60;
}

void Time::AddHr(int h)
{
    hours += h;
}

void Time::Reset(int h, int m)
{
    hours = h;
    minutes = m;
}

Time Time::operator+(const Time& t)const
{
    Time sum;
    sum.hours = hours;
    sum.minutes = minutes;
    sum.AddHr(t.hours);
    sum.AddMin(t.minutes);
    return sum;
}

Time Time::operator-(Time& t) 
{
    int tem_minutes = toMin() - t.toMin();
    if (tem_minutes < 0)
    {
        cout << "Are you kidding me??" << endl;
        Time dvalue;
        return dvalue;
    }
    else
    {
        Time dvalue(0, tem_minutes);
        return dvalue;
    }
}
Time Time::operator*(Time& t)
{
    int tem_minutes = toMin()*t.toMin();
    Time result(0,tem_minutes);
    return result;
}



void Time::Show()const
{
    cout << hours << "hours," << minutes << "minutes";
}

ostream& operator<<(ostream& om, const Time& t)
{
    om << t.hours << "hours," << t.minutes << "minutes";
    return om;
}

int main()
{
    Time t1(4, 30);//调用有参数的构造函数。
    Time t2(5, 70);
    (t1 + t2).Show(); //等价于 t1.operator+(t2).Show();
    Time t3(5, 300);
    cout << endl;
    t3.Show();
    cout << endl;
    cout << (t1 + t2 + t3) << endl;
    // 这里首先运算括号里的表达式,
    //t1+t2先被执行,返回一个临时的Time对象,这个对象再调用
    //operator+()函数,返回存储了最终运算结果的临时的Time对象
    //最后调用operator<<()友元函数。
    Time t4;
    cout << t4 << endl;
    cout << (t3 - t2)<<endl;
    cout << (t2 * t3);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值