C + + Reference learning:
Usually the first function is quoted, and one will think of the alias of the referenced variable, which is directly manipulated.
Declaration of reference:
Type + & + name (can be considered a constant pointer)
Note: (1) & is the function of identifiers;
(2) when declaring a reference, it must first be initialized;
(3) You cannot create a reference to an array because the array is composed of several elements, so you cannot create an alias for an array;
Referenced apps:
(Reference as parameter)
int swap (intint &b) { int t = A; = B; =
(Reference as constant)
int Main () { int; Const int &a = b; return 0 ;}
This can make the code more robust, and there are other requirements;
(Reference as return value)
Type + & + function name
(1) Return function value by reference, need to add &; in front of function name when defining function
(2) The greatest benefit of returning a function value with a reference is that it does not produce a copy of the returned value in memory.
When a function returns a stack variable, it cannot be the initial value of the other reference (because the stack variable is freed after the function ends)
int & Fun() { return A; When the authority variable is released, a reference to the local variable points to a memory space where it is unknown}int main () { int &a = Fun ();}
This is wrong.
And can not be left value;
The function returns a static or global variable: (both of these variables are placed in the global zone)
Can be used as a reference to other values, and can be left and right values;
Write a code in the following cases:
//return static variablesint&fun1 () {Static intA =1; returnA;}//return local Variablesint&fun2 () {intA =2; returnA;}//parameter is a reference to theint&FUN3 (int&a) { returnA;}intMain () {intA =fun1 (); int&b =fun1 (); cout<<"A =" <<a << Endl; cout<<"B =" <<b << Endl;}
/* Run the result as:
A = 1;
b = 1;
*/
This is because the parameters are global;
Main () { int a = fun2 (); int &b = fun2 ();} /* The result is 2 and-2 (negative indicates pointing to memory ambiguous)* /
Because this is a local variable, when the 2nd semicolon ends, it points to an ambiguous memory area;
Main () {
int c = Ten; int a = fun3 (c); int &b = fun3 (c);} /* The result of operation is a = ten; b = Ten; */
The reference is due to the existence of the program will not be released before the end;
References to C + +