The reference type is defined by the type identifier and an address fetch operator. The reference must be initialized.
See the following initialization:
Double dval = 3.14159;
Extern int F ();
Int & ir1 = 1024; // Error
Int & ir2 = dval; // Error
Int & ir3 = f (); // Error
The above three references will cause compilation errors during initialization.
In fact, the reference is stored inside an object address, which is the alias of the object. For unaddressable values, such as text constants and different types of objects, the compiler must generate a temporary object to implement the reference. The reference actually points to this object, but the user cannot access it. for example, we wrote:
Double dval = 3.14159;
Int & ir2 = dval;
Because type conversion is required, the compiler converts it:
Int temp = dval; Int & ir2 = temp; // If you assign a new value to ir2 at this time, the change is temp, not dval.
// While temp is unaddressable, it is not intended for users.
Therefore, in this case, we need to reference const because they are read-only and do not allow non-const references to point to objects or values that require temporary objects. in addition, the return value of Int & ir3 = f () and F () functions is also a temporary value and cannot be used to initialize non-const type references.
The correct modification is as follows:
Const Int & ir1 = 1024; // OK
Const Int & ir2 = dval; // OK
Const Int & ir3 = f (); // OK