As we all know, the C + + language has a very useful and very common technology is called reference, this is a C language based on a spread, similar to the pointer, just at the time of declaration with & replaced by the *, the reference can be considered as a reference to an alias, at the time of declaration must be initialized.
1. References to function parameters
#include <iostream>using namespacestd;voidSwapint&a,int&b);intMain () {intNUM1 =Ten; intnum2 = -; cout<<num1<<" "<<num2<<Endl; Swap (NUM1, num2); cout<<num1<<" "<<num2<<Endl; return 0;}voidSwapint&a,int&b) { inttemp =A; A=b; b=temp;}
2. Function reference return value
The non-void type function in C + + needs to return a return value, similar to a function parameter, and we can also declare the return value of a function as a reference. The normal function return value is returned by passing a value, and the result of the expression operation immediately following the return of the keyword is copied to a temporary storage space, and the function caller takes the function return value from the temporary storage space.
#include <iostream>using namespacestd;intValplus (int&a);intMain () {intNUM1 =Ten; intnum2; Num2=Valplus (NUM1); cout<<num1<<" "<<num2<<Endl; return 0;}intValplus (int&a) {a= A +5; returnA;}
The Valplus function takes a normal return value, and after adding 5 to the result of variable A, copies the result to a temporary storage space and then copies it from the temporary storage space to the NUM2 variable. When we declare a function return value as a reference, as shown in Example 5. Although example 5 run the result and example 4 is the same, but example 5 of the Valplus function after adding a variable 5, the result of its operation is directly copied to the num2, the middle is not copied to the temporary space, and then copied from the temporary storage space such a process. This is the difference between the normal return of a value and the return of a reference.
#include <iostream>using namespacestd;int& Valplus (int&a);intMain () {intNUM1 =Ten; intnum2; Num2=Valplus (NUM1); cout<<num1<<" "<<num2<<Endl; return 0;}int& Valplus (int&a) {a= A +5; returnA;}
C + + Reference