主要有以下两点:
1.当函数返回值为引用类型时,没有复制return的对象,而返回的是return的对象本身。
2.返回引用时,要求在函数的参数中,包含有以引用方式或指针方式存在的,需要被返回的参数。
实验代码如下:
#include <iostream>
using namespace std;
int a = 5;
int c = 2;
int &b = c;
int& add(int&);
int& add(int& x)
{
x=x+1;
cout<<"a="<<a<<endl;
cout<<"&x="<<&x<<endl;
return x;
}
int main()
{
cout<<&a<<endl;
cout<<&b<<endl;
cout<<&c<<endl;
cout<<add(a)<<endl;
cout<<&add(a)<<endl;
b = add(a);
cout<<b<<endl;
a++;
cout<<b<<endl;
int& d = add(a);
cout<<d<<endl;
a++;
cout<<d<<endl;
cout<<&d<<endl;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<&a<<endl;
cout<<&b<<endl;
cout<<&c<<endl;
return 0;
}
运行结果:
0x602070
0x602074
0x602074
a=6
&x=0x602070
6
a=7
&x=0x602070
0x602070
a=8
&x=0x602070
8
8
a=10
&x=0x602070
10
11
0x602070
11
8
8
0x602070
0x602074
0x602074
参考:https://www.cnblogs.com/fly1988happy/archive/2011/12/14/2286908.html