11.2.1 添加加法操作符
将Time类转换为重载的加法操作符很容易,只要将Sum(的名称改为operator+(即可。这样做是对
的,只要把操作符(这里为+)放到operator的后面,并将结果用作方法名即可。在这里,可以在标识符中
使用字母,数字或下划线之外的其他字符。程序清单11.4和11.5反映了这些细微的修改。
程序清单11.4 mytime1.h
// mytimet.h -- Time class after operator overloading
ifndef MYTIME1_H
Adefine MYTIME1_B
class Time
Private:
int hours:
int minutes:
public:
Tivell:
Time lint h. int n = 0);
void AddMin [int nh
woid AddHr (int h):
void Reset (int h = 0. int m = 0)
Time operator+ (comst Time & t) const:
void Show ()const:
fendif
程序清单11.5 mytime1.cpp
// mytimel.cpp -- implementing Time methods
tinclude <iostrean>
Winclode "mytimel.h"
Timet:Timel)
hours = minutes = D:
-
Time :: Time (int h, int m}
hours = h:
minutes = m:
void Time: :AddMin (int m)
minotes += m:
hours += minutes / 60:
minutes = 60:
void Time: :Ador (int h)
hours +w h:
1
-
void Tine :: Reset (int h. int m)
hours = ht
minutes = m;