C++递增运算符重载遇到的引用问题

C++递增运算符重载遇到的引用问题

近日学习黑马程序员的第123个C++视频 递增运算符重载 时遇到了一些问题,特此记录

左移运算符重载

在黑马的前一节视频,左移运算符重载时,代码如下

ostream& operator<<(ostream &cout,Person &p)//这里的p是用引用的方式传递的
{
	cout << "m_A = " << p.m_A << " m_B = " << p.m_B;
	return cout;
}

递增运算符重载

在学习递增运算符时,当我尝试直接复制上一节使用的左移运算符重载代码时,发生了错误,如下图所示(完整的代码在最后面)
在这里插入图片描述
错误聚焦在了第47行,编译器不认识cout<<myint++。

经过仔细对比发现左移运算符重载是用引用的方式传入myInt类,但后置递增运算符返回的是值传递,两者不匹配所以发生报错。
在这里插入图片描述
在这里插入图片描述

小结

返回的局部变量,不能以引用的形式作为另一个函数的传入参数。另外自己编程的时候也要注意当返回值是局部变量时,函数使用完,局部变量就销毁了,不能二次使用。我理解的还有不到位的地方,欢迎各位大佬指正。

改正前的源代码

#include <iostream>
using namespace std;

class myInt
{
	friend ostream& operator<<(ostream &cout, myInt& myint);
public:
	myInt()
	{
		m_int = 0;
	}

	//前置运算符
	myInt& operator++()
	{
		m_int++;
		return *this;
	}

	//后置运算符
	myInt operator++(int)
	{
		myInt temp = *this;
		m_int++;
		return temp;
	}

private:
	int m_int;
};

//重载<<运算符
ostream& operator<<(ostream& cout, myInt& myint)
{
	cout << "m_int = " << myint.m_int << endl;
	return cout;
}

void test01()
{
	myInt myint;


	cout << myint++ << endl;
	cout << ++myint << endl;
}

int main()
{
	test01();

}



改正后的源代码

#include <iostream>
using namespace std;

class myInt
{
	friend ostream& operator<<(ostream &cout, myInt myint);
public:
	myInt()
	{
		m_int = 0;
	}

	//前置运算符
	myInt& operator++()
	{
		m_int++;
		return *this;
	}

	//后置运算符
	myInt operator++(int)
	{
		myInt temp = *this;
		m_int++;
		return temp;
	}

private:
	int m_int;
};

//重载<<运算符
ostream& operator<<(ostream& cout, myInt myint)
{
	cout << "m_int = " << myint.m_int << endl;
	return cout;
}

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

int main()
{
	test01();

}




  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值