C++ Using references as return values
Using references instead of pointers makes C++ programs easier to read and maintain. C++ functions can return a reference in a manner similar to returning a pointer.
When a function returns a reference, it returns an implicit pointer to the return value. In this way, the function can be placed on the left side of an assignment statement. For example, consider the following simple program:
Example
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, be careful that the referenced object cannot go out of scope. Therefore, returning a reference to a local variable is illegal, but a reference to a static variable can be returned.
The following is an example that demonstrates returning a reference to a static variable:
Example
using namespace std;
// return a reference to a static variable
int& getStaticRef() {
static int num = 5; // static variable
return num;
}
int main() {
int& ref = getStaticRef(); // get a reference to a static variable
cout << "initial value:" << ref << endl;
ref = 10; // modify the value of the static variable
cout << "value after modification:" << ref << endl;
cout << "value after calling the function again:" << getStaticRef() << endl;
return 0;
}
The getStaticRef() function returns a reference to the static variable num.
The output result is:
初始值:5 修改后的值:10 再次调用函数后的值:10other extensions