2025年4月10日 星期四 乙巳(蛇)年 正月十一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > VC/VC++

C++重载++和--(自增自减运算符)

时间:01-05来源:作者:点击数:338

自增++和自减--都是一元运算符,它的前置形式和后置形式都可以被重载。请看下面的例子:

  • #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() 函数,之后再将先前保存的对象返回。在这个函数中参数n是没有任何意义的,它的存在只是为了区分是前置形式还是后置形式。

自减运算符的重载与上面类似,这里不再赘述。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门