1. 语法
返回类型 类名::operator 操作符(形参表)
{
函数体代码;
}
2. 实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73 |
#include <iostream> #include <ctime> using
namespace std; class
StopWatch{ public : StopWatch(); //构造函数 void
setTime( int
newMin, int
newSec); //设置秒表时间 StopWatch operator - (StopWatch&); //计算两个秒表的时间 void
showTime(); private : int
min; int
sec; }; StopWatch::StopWatch() { min=0; sec=0; } void
StopWatch::setTime( int
newMin, int
newSec) { min=newMin; sec=newSec; } StopWatch StopWatch::operator - (StopWatch& anotherTime) { StopWatch tempTime; int
seconds; //两个秒表时间间隔的秒数 seconds=min*60+sec-(anotherTime.min*60+anotherTime.sec); if (seconds<0) seconds=-seconds; tempTime.min=seconds/60; tempTime.sec=seconds%60; return
tempTime; } void
StopWatch::showTime() { if (min>0) cout<<min<< "minutes" <<sec<< "seconds\n" ; else cout<<sec<< "seconds\n" ; } int
main() { StopWatch startTime,endTime,usedTime; cout<< "按回车开始!" ; cin.get(); //等待用户输入 time_t
curtime= time (0); //获取当前系统时间 tm
tim=* localtime (&curtime); //根据当前时间获取当地时间 int
min,sec; min=tim.tm_min; //得到当地时间的分 sec=tim.tm_sec; //得到当地时间的秒 startTime.setTime(min,sec); cout<< "按回车结束!" ; cin.get(); //等待输入 curtime= time (0); tim=* localtime (&curtime); min=tim.tm_min; sec=tim.tm_sec; endTime.setTime(min,sec); usedTime=endTime-startTime; cout<< "用时。。。" ; usedTime.showTime(); return
0; } |
其中包含以下信息
a. 函数名是operator —,表示重载操作符 -;
b. StopWatch::表示重载该操作符的类是StopWatch类;
c. 该函数返回类型是StopWatch类型
d. 该函数带一个参数,参数类型是StopWatch类,并以引用的形式传。
原文:http://www.cnblogs.com/ccccnzb/p/3567530.html