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

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

相关推荐
「QT(C++)开发工程师」5 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天5 小时前
0 初识C++
开发语言·c++
FfHUCisI5 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI5 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
lemon_sjdk6 小时前
ObjectProperty
java·开发语言·算法
大模型码小白6 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
hh9506 小时前
Agent Plan x DeepSeek Harness:Agent 供应链安全与第三方插件审计
java·开发语言·安全·agent plan·adg成都社区·adg社区
「QT(C++)开发工程师」7 小时前
C++ std::move 详解
开发语言·c++
matlab代码7 小时前
基于matlab的玉米种子计数设计(GUI界面)【源码58期】
开发语言·matlab