C++ 43 之 自增运算符的重载

cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

class MyInt{
    friend ostream& operator<< (ostream& cout , MyInt& int1);
public:
    MyInt(){
        this->m_num = 0;
    }

    // 前置自增: 成员函数实现++运算符的重载 返回的是 引用&
    MyInt& operator++() { // 前置自增 需要返回的是引用,因为后续需要++(++X),不能是返回值,会调用复制构造函数
        this->m_num++;
        return *this;
    }
    // 后置自增:成员函数实现++运算符的重载 返回的值,而不是引用
    MyInt operator++(int){  //占位参数是int 就代表后置自增
        // 先记录初始状态的值,把本身的值+1后,返回的是临时变量
        MyInt temp = *this;
        this->m_num++;
        return temp;

    }

    // 隐式的转换为int类型:获取m_num的值  把int类型重载成m_num
    // 当你尝试将MyInt对象用作int时,会自动调用这个转换运算符来获取m_num的值。目的是让后面的int++正常
    operator int() const{
        return m_num;
    }

private:
    int m_num;

};

// 左移运算符重载
ostream& operator<< (ostream& cout , MyInt& int1){
    cout << int1.m_num;
    return cout;
}

int main()
{

    // 系统的++a
    // int a = 0;
    // cout << ++(++a) << endl;
    // cout << a++ << endl; // 0
    // cout << a << endl; // 1
    // cout << (a++)++ << endl; // 不能返回引用,而应该返回值才可以
    // cout << a << endl;

    // MyInt int1;
    // ++int1;


    // 前置
    // ++int1; // 写外面,返回值可以是void 
    // cout << ++(++int1) << endl; // 写在cout里面,返回值必须是引用类型的
    // cout << int1 << endl;

    // 后值的
    MyInt int1;
    cout << int1++ << endl; // 返回值是MyInt类型,当你把它当作int时会报错,需要进行类型转化  后置++ 只能加一次
    cout << int1 << endl;
    
  

    return 0;
}

调用代码时候,要优先使用前缀形式,除非确实需要后缀形式返回的原值,前缀和后缀形式语义上是等价的,输入工作量也相当,只是效率经常会略高一些,由于前缀形式少创建了一个临时对象。

相关推荐
西北大程序猿21 分钟前
单例模式与锁(死锁)
linux·开发语言·c++·单例模式
你不是我我31 分钟前
【Java开发日记】说一说 SpringBoot 中 CommandLineRunner
java·开发语言·spring boot
心扬43 分钟前
python网络编程
开发语言·网络·python·tcp/ip
qq_454175791 小时前
c++学习-this指针
开发语言·c++·学习
尘浮7281 小时前
60天python训练计划----day45
开发语言·python
sss191s1 小时前
校招 java 面试基础题目及解析
java·开发语言·面试
sduwcgg2 小时前
python的numpy的MKL加速
开发语言·python·numpy
钢铁男儿2 小时前
Python 接口:从协议到抽象基 类(定义并使用一个抽象基类)
开发语言·python
超闻逸事2 小时前
【题解】[UTPC2024] C.Card Deck
c++·算法
暴力求解2 小时前
C++类和对象(上)
开发语言·c++·算法