1 reference definition
C ++ is an important extension of C When referencing. The function of referencing is to give the variable an alias.
For example:
Int;
Int & B = a; // declare that B is a reference of
After the above statement, B becomes the alias of a. both a and B have the same status and role.
To declare B as a reference, you do not need to create new units for B. B and a occupy the same storage unit in the memory. They have the same address.
# Include <iostream> using namespace std; int main () {& nbsp; int a = 10; & nbsp; & nbsp; int & B = a; // declare that B is a reference & nbsp; cout <"B =" <B <endl; & nbsp; a = A-5; & nbsp; & nbsp; cout <"B =" <B <endl; & nbsp; B = B-1; & nbsp; cout <"a =" <a <endl; & nbsp; & nbsp; return 0 ;}
In the program,
Declares that B is a reference of a, and then outputs B = 10;
Then reduce the value of a by 5, and then output B = 5, which means that B will change with the change of;
Then reduce the value of B by 1, and then output a = 4, indicating that a will change with the change of B.
When declaring a reference, you must initialize it at the same time, that is, declare the variable that it represents. After declaring that variable B is a reference of variable a, you can use B as the alias of variable a, and B cannot be referenced as another variable (alias ).
Declare references without initialization:
#include<iostream> using namespace std; int main(){ int a=10; int &b; return 0; } #include<iostream>using namespace std;int main(){ int a=10; int &b; return 0;}