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
}
cpp_references.htm
廣告