#C++PrimerPlus# Chapter11_Exersice4_mytimeV4

修改Example10~12,将类定义中的运算符重载都改用友元函数实现。

显然,需要对mytime3.h,mytime3.cpp做修改,而usetime3.cpp不需要修改。

程序清单如下:


// mytime4.h

#ifndef MYTIME3_H_
#define MYTIME3_H_
#include <iostream>

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);
    friend Time operator+(const Time& t1, const Time& t2);
    friend Time operator-(const Time& t1, const Time& t2);
    friend Time operator*(const Time& t, double n);
    friend Time operator*(double n, const Time& t);
    friend std::ostream& operator<<(std::ostream& os, const Time& t);
};

#endif


// mytime4.cpp
#include <iostream>
#include "mytime4.h"

Time::Time()
{
    hours = 0;
    minutes = 0;
}
Time::Time(int h, int m)
{
    hours = h;
    minutes = m;
}
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 operator+(const Time& t1, const Time& t2)
{
    Time sum;
    sum.minutes = t1.minutes + t2.minutes;
    sum.hours = t1.hours + t2.hours + sum.minutes / 60;
    sum.minutes %= 60;
    return sum;
}
Time operator-(const Time& t1, const Time& t2)
{
    Time diff;
    int tot1, tot2;
    tot1 = t1.hours * 60 + t1.minutes;
    tot2 = t1.hours * 60 + t1.minutes;
    diff.hours = (tot1 - tot2) / 60;
    diff.minutes = (tot1 -tot2) % 60;
    return diff;
}
Time operator*(const Time& t, double n)
{
    Time result;
    long totalminutes = t.hours * 60 * n + t.minutes * n;
    result.hours = totalminutes / 60;
    result.minutes = totalminutes % 60;
    return result;
}
Time operator*(double n, const Time& t)
{
    return t * n;
}
std::ostream& operator<<(std::ostream& os, const Time& t)
{
    os << t.hours << ":" << t.minutes;
    return os;
}


 

结束。

 

 

 

posted @ 2013-05-04 20:20  庄懂  阅读(164)  评论(0编辑  收藏  举报