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类,并以引用的形式传。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· MQ 如何保证数据一致性?
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp