• c++ 学习 之 运算符重载 之 前置++和后置++


    前言

    	int a=1;
        cout << ++(++a) << endl;
        cout << a << endl;
        int b=1;
        cout << (b++)++ << endl;  // 这个是错误的
        cout << b << endl;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    上面样例中,
    前置 ++ 返回的是引用,所以a 的值变成了3
    后置 ++ 返回的不是可以改变的左值,所以有问题

    正文

    我们来看看下面的学习代码

    #define CRT_SECURE_NO_WARNINGS
    #include
    using namespace std;
    
    class MyInterger
    {
    
        friend ostream& operator<<(ostream& cout, MyInterger& p);
    public:
        MyInterger()
        {
            m_Num = 10;
        }
    
        // 前置++ 运算符重置
        MyInterger& operator++()
        {
            m_Num++;
            return *this;
        }
    
        // 后置 ++ 运算符重置
        // 返回值不能作为重载的区分条件
        MyInterger& operator++(int)  // int 代表一个占位参数,用于区分前置和后置++
        {
            // 先记录当时的结果
            MyInterger* tmp = new MyInterger(*this); // 在堆上分配一个 MyInterger 对象的副本
            // 后 递增
            m_Num++;
            // 最后将记录结果做返回
            return *tmp;
        }
    
    
    private:
        int m_Num;
    };
    
    ostream& operator<<(ostream& cout, MyInterger& p)
    {
        cout << p.m_Num;
        return cout;
    }
    
    void test()
    {
        MyInterger myint;
        cout << ++(++myint) << endl;
        cout << myint++ << endl;
    }
    
    int main()
    {
        
        test();
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
  • 相关阅读:
    有色噪声干扰下Hammerstein非线性系统两阶段辨识
    nginx负载均衡配置无效解决记录
    flutter库
    三十分钟学会zookeeper
    内存四区的基本概念
    期货自动止损止盈 易盛极星
    数据库2-mysql环境搭建
    Android---Gradle 构建问题解析
    ctfshow node.js专题
    JS中内存泄漏的几种情况
  • 原文地址:https://blog.csdn.net/wniuniu_/article/details/133380153