类和对象 第五部分第三小节:递增运算符重载

作用:通过重载递增运算符,实现自己的整型数据递增

代码案例

1.重载前置++运算符

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

class MyInteger {
    friend ostream& operator<<(ostream& out, const MyInteger& myint);

public:
    MyInteger() {
        m_Num = 0;
    }

    // 前置++
    MyInteger& operator++() {
        ++m_Num; // 先自增
        return *this; // 再返回
    }

private:
    int m_Num;
};

// 重载输出运算符
ostream& operator<<(ostream& out, const MyInteger& myint) {
    out << myint.m_Num;
    return out;
}

void test01() {
    MyInteger myInt;
    cout << ++myInt << endl;
}

int main() {
    test01();
    system("pause");
    return 0;
}

效果图:

注意,这边调用递增运算符要用引用的方式,保证递增始终在一个数据上而非其它变量,否则会出现结果不一致的情况,例如:

正确形式:

错误案例:

2.重载后置++运算符

后置递增使用值的原因:temp值为局部变量,使用完便被释放掉,而引用不能返回局部变量

相关推荐
Fairy_sevenseven9 分钟前
[1]python爬虫入门,爬取豆瓣电影top250实践
开发语言·爬虫·python
Young_Zn_Cu44 分钟前
LeetCode刷题记录(持续更新中)
算法·leetcode
天选之女wow1 小时前
【代码随想录算法训练营——Day31】贪心算法——56.合并区间、738.单调递增的数字、968.监控二叉树
算法·leetcode·贪心算法
lixinnnn.1 小时前
贪心:火烧赤壁
数据结构·c++·算法
小小前端_我自坚强1 小时前
前端算法相关详解
前端·算法
珹洺1 小时前
Java-Spring入门指南(二十一)Thymeleaf 视图解析器
java·开发语言·spring
Predestination王瀞潞1 小时前
类的多态(Num020)
开发语言·c++
Predestination王瀞潞1 小时前
类的继承(Num019)
开发语言·c++
Nuyoah11klay1 小时前
华清远见25072班C++学习假期10.3作业
c++
万粉变现经纪人1 小时前
如何解决 pip install -r requirements.txt 无效可编辑项 ‘e .‘(-e 拼写错误)问题
开发语言·python·r语言·beautifulsoup·pandas·pip·scipy