C++的递增重载中的运算符重载为什么不能传入后置递增的对象引用

C++的递增重载中的运算符重载为什么不能传入后置递增的对象引用

原因为:前置递增返回的是对象本身,而后置递增返回的是temp的值
具体看代码解释

#include <iostream>

using namespace std;

class integer
{

public:
	friend ostream& operator<<(ostream& cout, integer p);
	integer()
	{
		m_num = 10;
	}
	//如果不传回去引用就是克隆体去进行链式反应
	/*integer& operator--()
	{//前置
		this->m_num--;
		return *this;
	}*/
	//不能返回一个局部变量的引用
	integer operator--(int)
	{//后置
		integer temp = *this;
		m_num--;
		return temp;
	}
private:
	int m_num;
};
ostream& operator<<(ostream &cout,integer p)//为什么不用引用呢
{//因为后置递增函数返回的是temp
	cout << p.m_num; //引用的本质是一旦指向 指向不能更改
	return cout; //前置递增返回的是本身(可以用引用) 而后置递增返回的不是本身(是temp即返回的是值)
}
//void test01()
//{
//	integer p;
//	cout << "--p="<<--p << endl;
//	cout << "p=" << p << endl;
//}
void test02()
{
	integer p;
	cout << "p--=" << p-- << endl;
	cout <<"p=" << p << endl;
}
int main() 
{
	/*test01();*/
	test02();
	system("pause");

	return 0;
}
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值