zoukankan      html  css  js  c++  java
  • c++之递增运算符重载

    #include<iostream>
    using namespace std;
    
    class MyInteger {
        friend ostream& operator<<(ostream& cout, MyInteger myInteger);
    public:
        MyInteger() {
            num = 0;
        }
        //重载++i运算符
        //返回引用是为了对同一个数据进行递增操作
        MyInteger & operator++() {
            num++;
            return *this;
        }
        //重载i++运算符,int是占位符,后置递增要返回值
        MyInteger operator++(int) {
            //先记录当时结果
            MyInteger tmp = *this;
            //后递增
            num++;
            //再返回记录的结果
            return tmp;
        }
    private:
        int num;
    };
    
    ostream & operator<<(ostream &cout,MyInteger myInteger) {
        cout << "num=" << myInteger.num;
        return cout;
    }
    void test() {
        MyInteger myInteger;
        cout << ++(++myInteger)<<endl;
        cout << myInteger << endl;
    }
    
    void test2() {
        MyInteger myInteger;
        cout << myInteger++ << endl;
        cout << myInteger << endl;
    }
    
    int main() {
        test2();
        system("pause");
        return 0;
    }

    说明:

    1.如果

     MyInteger & operator++() {
            num++;
            return *this;
        }

    这里返回的是MyInteger而不是引用MyInteger &,在调用test()时,会输出:

    也就是没有达到++i类似的效果:先计算,后赋值。这是因为,当执行一遍++MyInteger后,再执行++(++MyInteger) ,此时这里的(++MyInteger)已经不再是原来的MyInteger对象了,所以++(++MyInteger) 的结果是2,而MyInteger的结果是1,因此采用&,操作的就是同一个对象。这之后再调用test(),输出为:

    要想实现另外一种自增,即i++,先赋值,后计算,就需要重载自增函数,只需要向重载函数中传入int占位符即可。同时,在函数里面,先要记录当前的值,再进行++,最后返回原先记录的值,这里返回的不能是引用,因为假设我们返回的是引用,相当于返回的是tmp的引用,而tmp是一个局部变量,在函数运行完后就会释放,此时再去访问该地址,就不合法了。最后调用test2(),输出为:

  • 相关阅读:
    layui穿梭框右侧增加上移下移功能
    java.lang.NullPointerException出现的几种原因:
    springboot+thymeleaf+mybatis 基础学习
    Vue 生命周期扫盲
    Token 认证(Asp.Net)
    从具体化“system.decimal”类型到“system.string”类型的指定强制转换无效
    【C#】委托和Lambda表达式
    Visual Studio 2017添加visionPro控件
    从WinForm程序中看委托和事件
    西门子PLC通讯-仿真环境搭建
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12097896.html
Copyright © 2011-2022 走看看