天天看点

C++ 初学 引用做函数返回值

首先,问题是拿函数返回其引用,值的释放问题。

1 返回局部变量引用:

直接上源码看效果:

#include<iostream>
using namespace std;


//引用做函数返回值
//返回局部变量引用
int& test01() {

	int a = 10;
	return a;
}


int main()
{
	
	//不能返回局部变量引用
	int& ref = test01();
	//局部变量已经被释放,因为编译器做了保留,第二次输出结果就会错误 
	cout << "ref = " << ref << endl;//输出 10
	cout << "ref = " << ref << endl;//输出乱码
	system("pause");
	return 0;
}           

结果:第一次输出是10,正确;第二次输出乱码,错误。

ref = 10
ref = 2077342096
请按任意键继续. . .
           
#include<iostream>
using namespace std;


//引用做函数返回值
//返回局部变量引用
int& test01() {

	int a = 10;
	return a;
}
//返回静态变量引用
int& test02() {

	static int a = 10;//静态变量。存放在全局区,全局区上的数据在程序结束后系统释放
	return a;
}

int main()
{
	
	//不能返回局部变量引用
	//int& ref = test01();
	//局部变量已经被释放,因为编译器做了保留,第二次输出结果就会错误 
	//cout << "ref = " << ref << endl;//输出 10
	//cout << "ref = " << ref << endl;//输出乱码

	int& ref2 = test02();
	cout << "ref2 = " << ref2 << endl;
	cout << "ref2 = " << ref2 << endl;
	test02() = 1000; //如果函数的返回值是引用。这个函数的调用可以作为左值
	cout << "ref2 = " << ref2 << endl;
	cout << "ref2 = " << ref2 << endl;
	system("pause");
	return 0;
}           
ref2 = 10
ref2 = 10
ref2 = 1000
ref2 = 1000
请按任意键继续. . .