1
2
3
4
5
int& DoubleValue(int nX)
{
int nValue = nX * 2;
return nValue; // return a reference to nValue here
} // nValue goes out of scope here
看到这里的问题?的功能是试图返回一个参考值,将超出范围时,该函数返回。这意味着呼叫者接收一参考垃圾。幸运的是,你的编译器会如果你尝试这样做,给你一个错误。
引用返回通常用于返回引用的函数返回给调用者传递的参数。在下面的例子中,我们返回(参考)的阵列,通过引用传递给我们的功能元件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// This struct holds an array of 25 integers
struct FixedArray25
{
int anValue[25];
};
// Returns a reference to the nIndex element of rArray
int& Value(FixedArray25 &rArray, int nIndex)
{
return rArray.anValue[nIndex];
}
int main()
{
FixedArray25 sMyArray;
// Set the 10th element of sMyArray to the value 5
Value(sMyArray, 10) = 5;
cout << sMyArray.anValue[10] << endl;
return 0;
}