码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-09-01 21:36:28      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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

#include <iostream>
#include <iomanip>
using namespace std;
class stopwatch{  //秒表
private:
    int min;  //分钟
    int sec;  //秒钟
public:
    stopwatch(): min(0), sec(0){ }
    void setzero(){ min = 0; sec = 0; }
    stopwatch run();  // 运行
    stopwatch operator++();  //++i,前置形式
    stopwatch operator++(int);  //i++,后置形式
    friend ostream & operator<<( ostream &, const stopwatch &);
};
stopwatch stopwatch::run(){
    ++ sec;
    if( sec == 60 ){
        min ++;
        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.min<<":"<<setw(2)<<s.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;
}

上面的代码定义了一个简单的秒表类,min 表示分钟,sec 表示秒钟,setzero() 函数用于秒表清零,run() 函数是用来描述秒针前进一秒的动作,接下来是三个运算符重载函数。

先来看一下 run() 函数的实现,run() 函数一开始让秒针自增,如果此时自增结果等于60了,则应该进位,分钟加1,秒针置零。

operator++() 函数实现自增的前置形式,直接返回 run() 函数运行结果即可。

operator++ (int n) 函数实现自增的后置形式,返回值是对象本身,但是之后再次使用该对象时,对象自增了,所以在该函数的函数体中,先将对象保存,然后调用一次 run() 函数,之后再将先前保存的对象返回。在这个函数中参数n是没有任何意义的,它的存在只是为了区分是前置形式还是后置形式。

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

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

标签:

原文地址:http://www.cnblogs.com/Caden-liu8888/p/5831249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!