I:
You can define a function as a reference type. At this time, the return value of the function is the reference (alias) of a variable. Therefore, it is equivalent to returning a variable.
Value assignment. This is similar to the return value of a function as the pointer type. Because the reference type returned by a function call is generated after the function is run, the function does not
Can Return automatic variables and parameters. The reference of the returned variable. The variable must be a global variable or a static local variable, that is, a variable stored in the static zone.
Let's look at an example:
[Cpp] view plaincopy
/*
* Main. cpp
*
* Created on: 2012-9-18
* Author: china
*
* Note: because the reference type returned by a function call is generated after the function is executed, the function cannot return automatic variables and parameters.
The reference of the returned variable. The variable must be a global variable or a static local variable, that is, a variable stored in the static zone.
*
*/
# Include <iostream>
Using namespace std;
Int a = 4;
// The function returns a reference, that is, the alias of !!!!
Int & f (int x ){
// Static int a = 4; same effect as global variables
A = a + x;
Return;
}
Int main (int argc, char ** argv ){
Int t = 5;
Cout <f (t) <endl; // output 9 (a = 9) t = 5
F (t) = 20; // call first, then assign a value of a = 20 t = 5
Cout <f (t) <endl; // output 25 (a = 25) t = 5
T = f (t); // call first, then assign a value of a = 30, t = 30
Cout <f (t) <endl; // 60
Return 0;
}
(2): We all know that a function, as a program entity, has a name, type, address, and storage space. Generally, a function cannot be left (that is, a function cannot be placed in
Value to the left ). However, if the function is defined as the return reference type, because the returned variable alias, you can put the function on the left, that is, assign a value to the variable.
Eg:
[Cpp]
Eg :/*
* Main. cpp
*
* Created on: 2012-9-18
* Author: china
*
* We all know that a function, as a program entity, has a name, type, address, and storage space,
* Generally, a function cannot be used as the left value (that is, a function cannot be placed on the left of a value assignment ). However, if you define a function as a return reference type,
* Because a variable alias is returned, you can place the function on the left, that is, assign a value to the variable.
*
*/
# Include <iostream>
Using namespace std;
Int & f (int & x );
Int main (int argc, char ** argv ){
Int a = 3;
Cout <f (a) <endl; // a = 4, output 3
F (a) = 20; // call first and assign a value to a = 5
A + = 5; // a = 10
Cout <f (a) <endl; // 10
A = f (a); // a = 11, which is called first and then assigned a value
Cout <f (a) <endl; // 11, a = 12
Return 0;
}
Int & f (int & x)
{
Static int t = 2;
T = x ++;
Return t;
}