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;
    }
  • 相关阅读:
    vue-router路由器的使用
    组件间数据传递
    引用模块和动态组件
    vue自定义全局和局部指令
    vue实例的属性和方法
    vue生命周期以及vue的计算属性
    vue 发送ajax请求
    安装vue-cli脚手架
    vue指令详解
    scrapy-redis组件的使用
  • 原文地址:https://www.cnblogs.com/dracohan/p/3814870.html
Copyright © 2011-2022 走看看