C++ 通过引用返回值
使用引用而不是指针可以使C++程序更易读和维护。类似于返回指针,C++函数也可以返回引用。
当函数返回一个引用时,实际上返回的是其返回值的隐式指针。这样,函数可以在赋值语句的左侧使用。例如,考虑下面这个简单的程序−
#include <iostream>
#include <ctime>
using namespace std;
double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};
double& setValues( int i ) {
return vals[i]; // return a reference to the ith element
}
// main function to call above defined function.
int main () {
cout << "Value before change" << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
setValues(1) = 20.23; // change 2nd element
setValues(3) = 70.8; // change 4th element
cout << "Value after change" << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
return 0;
}
当上述代码编译并执行时,会产生以下结果−
Value before change
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
vals[3] = 24.1
vals[4] = 50
Value after change
vals[0] = 10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
vals[4] = 50
当返回一个引用时,要注意所引用的对象不要超出作用域。因此,返回对局部变量的引用是不合法的。但你可以始终返回对静态变量的引用。
int& func() {
int q;
//! return q; // Compile time error
static int x;
return x; // Safe, x lives outside this scope
}