A reference in C + + is the equivalent of an alias to a variable.
int a,j=3; int &b=a; B=j;
where b appears, it is equivalent to a, and b is replaced by a.
Attention:
1. References must be initialized at the time of declaration.
2. After initialization, the reference is the equivalent of that variable. And this app can no longer point to other variables.
3. The reference itself does not occupy memory and the system does not allocate memory.
4. A reference to an array:
int a_a[10]={0}; int (&a_b) [10]=a_a;
In fact: 1 and 2 sum up a bit like a constant pointer.
int &b=a; int * Const c=&a;
like C and B, declarations must be initialized.
Like C and B, you can no longer point to other content.
An interesting thing to do:
When can an already initialized reference point to another variable? To judge the correctness of 2.
Class A{public:a (int& _a): A (_a) {}private:int& A;}; int main () { int i=1,j=2; Aa (i); Ab (j); a=b; Error System ("pause"); return 0;}
This is interesting, A's a is a reference to I, B's A is a reference to J, A=b assignment operation, the system thinks we want to change a to a reference to J. It is illegal to do so.
Think: The system-provided assignment operation is not A.A=B.A? And this is obviously legal.
In fact, the system provides the default assignment operation is not simply the variable and variable =, so simple ah.
When a member variable of a class is a reference,
1> This variable must be assigned a value in the constructor's initialization list and cannot be assigned a = sign within the constructor function.
Class a{public:a (int i): b (i) {}private:int & B;};
2> the object of this class is not assignable. As in the above example.
References to C + +