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;
}

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

相关推荐
坚定学代码2 分钟前
认识 ‘using namespace‘
c++
jiang_changsheng7 分钟前
环境管理工具全景图与深度对比
java·c语言·开发语言·c++·python·r语言
LYOBOYI12313 分钟前
qml的对象树机制
c++·qt
yong999017 分钟前
MATLAB面波频散曲线反演程序
开发语言·算法·matlab
LeoZY_21 分钟前
开源项目精选:Dear ImGui —— 轻量高效的 C++ 即时模式 GUI 框架
开发语言·c++·ui·开源·开源软件
Fightting8821 分钟前
Tkinter Button bind hover message
开发语言·python
qq_3363139335 分钟前
javaweb-web基础(springboot入门)
java·开发语言·mysql
玄同7651 小时前
LangChain 1.0 模型接口:多厂商集成与统一调用
开发语言·人工智能·python·langchain·知识图谱·rag·智能体
特立独行的猫a1 小时前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
fie88891 小时前
基于C#的推箱子小游戏实现
开发语言·c#