Latest web development tutorials

C ++ as the return value of the reference

C ++ references C ++ references

By using references instead of pointers, C ++ makes programs easier to read and maintain. C ++ function can return a reference, and returns a pointer to a similar manner.

When the function returns a reference, it returns a pointer to the implicit return value. Thus, the function can be placed in the left side of an assignment statement. For example, consider the following simple procedure:

#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];   // 返回第 i 个元素的引用
}
 
// 要调用上面定义函数的主函数
int main ()
{
 
   cout << "改变前的值" << endl;
   for ( int i = 0; i < 5; i++ )
   {
       cout << "vals[" << i << "] = ";
       cout << vals[i] << endl;
   }
 
   setValues(1) = 20.23; // 改变第 2 个元素
   setValues(3) = 70.8;  // 改变第 4 个元素
 
   cout << "改变后的值" << endl;
   for ( int i = 0; i < 5; i++ )
   {
       cout << "vals[" << i << "] = ";
       cout << vals[i] << endl;
   }
   return 0;
}

When the above code is compiled and executed, it produces the following results:

改变前的值
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
vals[3] = 24.1
vals[4] = 50
改变后的值
vals[0] = 10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
vals[4] = 50

When returning a reference, pay attention to the referenced object can not go out of scope. It returns a reference to a local variable is not legal, however, you can return a reference to a static variable.

int& func() {
   int q;
   //! return q; // 在编译时发生错误
   static int x;
   return x;     // 安全,x 在函数作用域外依然是有效的
}

C ++ references C ++ references