专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

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

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/17 13:35:36       共计:3627 浏览
自增++和自减--都是一元运算符,它的前置形式和后置形式都可以被重载。请看下面的例子:
#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是没有任何意义的,它的存在只是为了区分是前置形式还是后置形式。

自减运算符的重载与上面类似,这里不再赘述。
版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:C++重载new和delete运算符详解 | ·下一条:C++重载[](下标运算符)详解

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有