1: If special instructions are not added, it is generally assumed that references refer to lvalue references. A reference is actually an implicit pointer, which creates an alias for an object, which is implemented by operator &, in the following form:
data types & expressions;
For example:
int a=10;
int & ia=a;
ia=2;
The above program defines a reference variable IA, which is the alias of the variable name A, and the operation on IA is exactly the same as for a. "Ia=2" assigns 2 to A, "&ia" returns the address of a. Perform "ia=2" and perform "a=2" equivalence.
The instructions for using the reference are as follows:
(1) once a C + + reference is initialized, it cannot be used to refer to another object and it cannot be re-constrained.
(2) A reference variable is just an alias for another object, and its operation has the same effect as the original object's operation.
(3) The pointer variable and the reference main difference has two points: first, the pointer is a data type, and the reference is not a data type, the pointer can be converted to the data type of the variable it points to, so that the assignment operator on both sides of the type to match, while using the reference, the system requires the reference and variable data type must Otherwise, data type conversions cannot be performed. The second is that both the pointer variable and the reference variable are used to point to other variables, but the syntax used by the pointer variable is more complex; After the reference variable is defined, it is used in the same way as the normal change.
For example:
int A;
int *pa=&a;
int & ia=a;
The sample code is as follows:
//5.16.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>using namespacestd;voidMain () {intA; int& ref_a =A; A= -; cout<<"a="<< a <<Endl; cout<<"ref_a="<< ref_a <<Endl; A=2; cout<<"a="<< a <<Endl; cout<<"ref_a="<< ref_a <<Endl; intb = -; ref_a=b; cout<<"a="<< a <<Endl; cout<<"ref_a="<< ref_a <<Endl; ref_a--; cout<<"a="<< a <<Endl; cout<<"ref_a="<< ref_a <<Endl;}
View Code
Operation Result:
Introduction to C + + Classic-Example 5.16-output reference