引用在作为递增函数重载和左移运算符重载时做形参遇见的问题

代码如下:

#include<iostream>
using namespace std;
#include<string>
class father
{
friend	void func();
friend ostream& operator<<(ostream& cout, father f);
public:
	father& operator++()//引用的本质在于返回自己本身,能够让后续的编程实现作用到自己
	{
		M_age++;
		return *this;
	}
	father operator++(int)
	{
		father temp = *this;//后置递增先记录自己
		M_age++;
		return temp;
	}
	
private:
	int M_age=0;
};
ostream& operator<<(ostream& cout, father f)//本质为cout<<f;也就是operator<<(cout,f);
{
	cout << f.M_age;
		return cout;
}
void func()
{
	father f;
	cout << ++f<< endl;
	cout << f << endl;
	cout << f++;
	cout << f << endl;

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

在这里我们可能疑惑这行代码

ostream& operator<<(ostream& cout, father f)

为什么father f在做形参的时候不可以也是引用呢?
下面我们来看一下代码:



#include<iostream>
using namespace std;
#include<string>
class father
{
friend	void func();
friend ostream& operator<<(ostream& cout, father& f);
public:
	father& operator++()//引用的本质在于返回自己本身,能够让后续的编程实现作用到自己
	{
		M_age++;
		return *this;
	}
	father operator++(int)
	{
		father temp = *this;//后置递增先记录自己
		M_age++;
		return temp;
	}
	
private:
	int M_age=0;
};
ostream& operator<<(ostream& cout, father& f)//本质为cout<<f;也就是operator<<(cout,f);
{
	cout << f.M_age;
		return cout;
}
void func()
{
	father f;
	cout << ++f<< endl;
	cout << f << endl;
	//cout << f++;当采用引用的时候,这里无法运行,因为引用无法用匿名变量来初始化
	cout << f << endl;

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

这里我们采用引用的方式传参。但是却无法输出

cout << f++;

为什么呢?我在代码注释的后面坐了解释:
当采用引用的时候,这里无法运行,因为引用无法用匿名变量来初始化(很重要!!!)
我们知道c++运行后置递增的时候返回的是一个匿名变量,由编译器暂时给出,代码举例如下:

int a = 0;
cout << a++ << endl;
cout<<a<<endl;

这里一个输出的结果为0,第二个结果才为1,所以在后置递增输出的时候,我们首先返回的是一个由编译器暂时给出的匿名变量,而匿名变量是无法初始化引用的,引用的本质是取别名,也是指针常量,所以初始化引用是需要一个常量的,也就是一块空间,而匿名变量是不能拿来初始化引用的。所以上面假设采用引用作为返回值的时候,

cout << f++;

是返回不了的。
总结如下:
匿名变量不能初始化引用!!!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潜渊@龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值