C++返回引用类型:
当返回一个变量时,会产生拷贝。当返回一个引用时,不会发生拷贝,你可以将引用看作是一个变量的别名,就是其他的名字,引用和被引用的变量其实是一个东西,只是有了两个名字而已。返回指向函数调用前就已经存在的对象的引用是正确的。当不希望返回的对象被修改时,返回const引用是正确的。
1.返回局部栈对象的引用是无效的。
从下面的代码中运行结构中我们可以看见,函数int &fun()中a的地址与主调函数中的C的地址是不一样的,可以看出变量c并不是fun() 函数a的引用(如果是引用,两者是共享一个内存空间,即内存地址是一样的),而是一个拷贝。fun()函数中a是一个局部变量,存在栈上,当fun()函数运行结束,这个变量的内存空间将释放。
一个栈对象的是无效的我们比如:
#include"stdafx.h"
#include<iostream>
using namespace std;
int &fun();
int _tmain(int argc,_TCHAR* argv[])
{
int c=fun();
cout<<"the address ofa:"<<&c<<endl;
cout<<"the value of a:"<<c<<endl;
return 0;
}
int &fun()
{
int a;
a=10;
cout<<"the address ofa:"<<&a<<endl;
cout<<"the value ofa:"<<a<<endl;
return a;
}
运行结果截图:
2. 2,返回引用,要求在函数的参数中,包含有以引用方式或指针方式存在的,需要被返回的参数。比如:
<pre name="code" class="cpp">#include "stdafx.h"
#include<iostream>
using namespace std;
int &fun(int &d);
int _tmain(int argc, _TCHAR* argv[])
{
int d;
d=10;
int &c=fun(d);
cout<<"the address of c:"<<&c<<endl;
cout<<"the value of c:"<<c<<endl;
cin>>c;
return 0;
}
int &fun(int &d)
{
d=30;
cout<<"the address of d:"<<&d<<endl;
cout<<"the value of d:"<<d<<endl;
return d;
}
运行结果截图: