目录

参考为返回值(Reference as Return Value)

通过使用引用而不是指针,可以使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

返回引用时,请注意引用的对象不会超出范围。 因此,返回对local var的引用是不合法的。 但是您总是可以返回静态变量的引用。

int& func() {
   int q;
   //! return q; // Compile time error
   static int x;
   return x;     // Safe, x lives outside this scope
}
↑回到顶部↑
WIKI教程 @2018