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

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

相关推荐
xiaowu08022 分钟前
C# task任务异步编程提高UI的响应性
开发语言·c#
kill bert2 小时前
Java八股文背诵 第四天JVM
java·开发语言·jvm
低头专研4 小时前
Markdown标题序号处理工具——用 C 语言实现
c语言·开发语言·typora·markdown文件标题编号·md文件标题序号
刚入门的大一新生6 小时前
C++初阶-C++入门基础
开发语言·c++
你是理想6 小时前
wait 和notify ,notifyAll,sleep
java·开发语言·jvm
forestsea6 小时前
Python进阶编程总结
开发语言·python·notepad++
q567315236 小时前
使用Java的HttpClient实现文件下载器
java·开发语言·爬虫·scrapy
weixin_428498497 小时前
Visual Studio 中使用 Clang 作为 C/C++ 编译器时,设置优化选项方法
c语言·c++·visual studio
菜鸡中的奋斗鸡→挣扎鸡7 小时前
第十四届蓝桥杯大赛软件赛省赛C/C++ 大学 B 组
c语言·c++·蓝桥杯
六bring个六7 小时前
QT上位机笔记
开发语言·笔记·qt