自增++和自减--都是一元运算符,它的前置形式和后置形式都可以被重载。请看下面的例子:
#include <iostream> #include <iomanip> using namespace std; //秒表类 class stopwatch{ public: stopwatch(): m_min(0), m_sec(0){ } public: void setzero(){ m_min = 0; m_sec = 0; } stopwatch run(); // 运行 stopwatch operator++(); //++i,前置形式 stopwatch operator++(int); //i++,后置形式 friend ostream & operator<<( ostream &, const stopwatch &); private: int m_min; //分钟 int m_sec; //秒钟 }; stopwatch stopwatch::run(){ ++m_sec; if(m_sec == 60){ m_min++; m_sec = 0; } return *this; } stopwatch stopwatch::operator++(){ return run(); } stopwatch stopwatch::operator++(int n){ stopwatch s = *this; run(); return s; } ostream &operator<<( ostream & out, const stopwatch & s){ out<<setfill('0')<<setw(2)<<s.m_min<<":"<<setw(2)<<s.m_sec; return out; } int main(){ stopwatch s1, s2; s1 = s2++; cout << "s1: "<< s1 <<endl; cout << "s2: "<< s2 <<endl; s1.setzero(); s2.setzero(); s1 = ++s2; cout << "s1: "<< s1 <<endl; cout << "s2: "<< s2 <<endl; return 0; }
运行结果:
s1: 00:00
s2: 00:01
s1: 00:01
s2: 00:01
上面的代码定义了一个简单的秒表类,m_min 表示分钟,m_sec 表示秒钟,setzero() 函数用于秒表清零,run() 函数是用来描述秒针前进一秒的动作,接下来是三个运算符重载函数。
先来看一下 run() 函数的实现,run() 函数一开始让秒针自增,如果此时自增结果等于60了,则应该进位,分钟加1,秒针置零。
operator++() 函数实现自增的前置形式,直接返回 run() 函数运行结果即可。
operator++ (int n) 函数实现自增的后置形式,返回值是对象本身,但是之后再次使用该对象时,对象自增了,所以在该函数的函数体中,先将对象保存,然后调用一次 run() 函数,之后再将先前保存的对象返回。<span
© 版权声明
本文刊载的所有内容,包括文字、图片、音频、视频、软件、程序、以及网页版式设计等部门来源于互联网,版权均归原作者所有!本网站提供的内容服务于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯本网站及相关权利人的合法权利。
联系信息:邮箱aoxolcom@163.com或见网站底部。
联系信息:邮箱aoxolcom@163.com或见网站底部。
THE END














请登录后发表评论
注册
社交帐号登录