区分operator++()是前缀还是后缀自增
发布日期:2021-09-12 06:44:51 浏览次数:2 分类:技术文章

本文共 740 字,大约阅读时间需要 2 分钟。

当我们重载了++这个自增运算符,那么在调用他的时候,编译器如何知道我们是调用了前缀自增还是后缀自增呢

#include 
using namespace std;class tmp {private: int a;public: tmp(int b) { a = b; } tmp& operator++(); //这是前缀 const tmp operator++(int); //这是后缀 void show();};tmp& tmp::operator++() { this->a += 1; return *this;}const tmp tmp::operator++(int) { tmp old = *this; //先拿到自增前的值 this->a += 1; //再自增 return old;}void tmp::show() { int i = 1; cout << "++a\n" << ++a + i << endl; cout << "a++\n" << i + a++ << endl;}int main(){ int i = 1; tmp a(1); a.show();}

输出结果

++a3a++3

通过形参列表的int参数来区分前缀后缀,尽管这个int参数并没有用到

注意前缀返回的是对象的引用,后缀返回的是const对象
至于为什么是const,这是因为,我们应该尽量和内置类型的行为保持一致,例如int就不允许i++++的操作,如果不返回一个const,就会导致我们不期望的++++行为发生

转载地址:https://blog.csdn.net/weixin_36888577/article/details/79890076 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:c++优先队列(priority_queue)用法详解
下一篇:error : default argument given for parameter 2 of

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月18日 01时30分39秒