The reference reference is sometimes referred to as Alias aliases, as shown in the following example:
int m=0;
int &n=m;
N=1;
cout<< "n" <<n<<endl;
cout<< "M" <<m<<endl;
& means that n is a reference to M, that is, an alias, and any action on N is an operation on M.
So n is neither a copy of M nor a pointer to M, in fact N is M itself.
When you assign a value of N to 1, the value of M also changes to 1
The primary function of a reference is the parameter and return value of the passed function.
In the C + + language, the parameters and return values of a function are passed in three ways: value passing, pointer passing, and reference passing.
The following example demonstrates these three different ways of passing.
//reference passing, variable n is a reference to the external variable num, n and num are the same thing, changing the value of n will change numvoidChangenumbyr (int&N) {N= -;}//Pointer passing, pointer p is a pointer to an external variable num, changing the contents of the pointer will cause the value of num to changevoidCHANGENUMBYP (int*p) {*p = -;}//value is passed, the variable n is a copy of the pass parameter num, and changing the value of n does not affect NUMvoidCHANGENUMBYV (intN) {N= -;}intMain () {intnum;//Referencesnum =Ten; Changenumbyr (num); cout<<"Changenumbyr"<<num<<Endl;//Pointersnum =Ten; Changenumbyp (&num); cout<<"Changenumbyp"<<num<<Endl;//valuenum =Ten; changenumbyv (num); cout<<"Changenumbyv"<<num<<Endl;system ("Pause");}
Operation Result:
In contrast to the above three sample programs, it is found that the nature of "reference passing" is like "pointer passing", while writing is like "value passing".
In fact, "reference" can Do Anything "pointer" also can do, why also "reference" this thing?
The answer is "do the right thing with the proper tools."
Pointers can manipulate anything in memory without restraint, although pointers are powerful, but very dangerous.
If you really only need to borrow an "alias" for an object, use "reference" instead of "pointer" to avoid an unexpected occurrence.
C + + Reference and pointers