zoukankan      html  css  js  c++  java
  • 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=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;
    }
  • 相关阅读:
    好用的视频播放器
    如何屏蔽weGame今日推荐窗口
    存一个大佬的地图编辑器
    过渡页面,加载进度
    Lua中正弦,余弦函数的使用
    如何替换loadingBar的底图
    使用精灵帧缓存替换纹理
    setTexture和loadTexture之间的区别
    我胡汉三又回来了
    python中单斜杆和双斜杠的区别
  • 原文地址:https://www.cnblogs.com/dracohan/p/3814870.html
Copyright © 2011-2022 走看看