首页 > 代码库 > c++前缀和后缀++

c++前缀和后缀++

1,c++规定后缀形式的++操作符有一个int行的参数,被调用时,编译器自动加一个0作为参数给他

2,前缀返回一个reference,后缀返回一个const对象

///////////////////////////////////////////////////////////////////////////////////  FileName    :   meffect_item5.h//  Version     :   0.10//  Author      :   Ryan Han//  Date        :   2013/11/18//  Comment     :  prefix and postfix/////////////////////////////////////////////////////////////////////////////////#ifndef MEFFECT_ITEM5_H#define    MEFFECT_ITEM5_H#include <iostream>using namespace std;class A{    friend ostream& operator <<(ostream &os, const A &a);public:    A(int initvalue=http://www.mamicode.com/0, int initstep=1):value(initvalue), step(initstep){}    //prefix    A& operator++(){        cout << "A& operator++() was called" << endl;        value+=step;        return *this;    }    //postfix    const A operator++(int){        cout << "const A operator++(int) was called." << endl;        const A oldA = *this;        ++(*this);        return oldA;    }private:    int value;    int step;};#endif
///////////////////////////////////////////////////////////////////////////////////  FileName    :   meffect_item5.cpp//  Version     :   0.10//  Author      :   Ryan Han//  Date        :   2013/11/18//  Comment     :  prefix and postfix/////////////////////////////////////////////////////////////////////////////////#include <iostream>#include "meffect_item5.h"using namespace std;ostream& operator<<(ostream &os, const A&a){    return os<<a.value;}int main(){    int i = 5;    //postfix return a const value    //i++++;        //prefix return a reference    ++++i;    A a(0,10);    cout << a++ << endl;    cout << ++a << endl;    A b(0,10);    cout << b.operator++(9) << endl;    cout << b.operator++() << endl;    return 0;}