Course list http://www.c-jump.com/bcc/
A C++ reference is like a pointer, except:
Usage syntax is like an object
References always refer to something
References can't be reassigned to something else
This is enforced by:
Requiring initialization in case of variables
The implicit reference initialization in case of function parameters
No syntax exists to changing the referent (the object that a reference is pointing to)
Once instantiated, the reference becomes eternal synonym for an object or a variable
void swap( int& left, int& right )
{
int temp = left;
left = right;
right = temp;
}
void f()
{
int x = 8;
int i = 4;
int& ri = i;
++ri; // now i == 5
ri = x; // now i == 8
int& ref2 = 2; // error, RHS must be an lvalue
}
Given:
int i = 4;
int x = 8;
int& r = i;
Silly attempts to get r to refer to x instead of i:
r = x; // NO: now i == 8
int& r = x; // NO: variable redefinitions are illegal
r = &x; // NO: type mismatch, r not a pointer-type
r& = x; // NO: plain syntax error
&r = &x; // NO: left operand must be l-value
Conclusion: r refers to i for r's entire life.
|
|