修改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;
}
结束。
原文链接: https://www.cnblogs.com/zhuangdong/archive/2013/05/04/3059954.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/87069
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!