> once initialized, a reference cannot be made refer to another variable
Yes.
> because it, the reference is treated as a const pointer.
No. The reference is treated as another identifier (an alias) that refers to the object it was initialized to refer to.
1 2
|
int i = 10, j =- 20 ;
int& r = i ;
|
Both
i and
r refer to the same int object. Throughout the life of
i,
i will continue to refer to the same int object. Throughout the life of
r,
r will also continue to refer to the same int object that
i referes to.
Therefore, these two lines are equivalent:
1 2
|
i = &j ; // error: invalid conversion from 'int*' to 'int'
r = &j ; // error: invalid conversion from 'int*' to 'int'
|
1 2 3 4 5 6 7
|
int main()
{
int i = 10, j = 20 ;
int& r = i ;
i = &j ;
r = &j ;
}
|
> g++ --std=c++11 -c test.cc
test.cc: In function 'int main()':
test.cc:5:10: error: invalid conversion from 'int*' to 'int' [-fpermissive]
test.cc:6:10: error: invalid conversion from 'int*' to 'int' [-fpermissive]
> g++ -fpermissive -c test.cc
test.cc: In function 'int main()':
test.cc:5:10: warning: invalid conversion from 'int*' to 'int' [-fpermissive]
test.cc:6:10: warning: invalid conversion from 'int*' to 'int' [-fpermissive] |
With -fpermissive, the (possibly narrowed or widened) numeric value of an address will be assigned to
i. The effect would be the same as writing :
1 2
|
i = reinterpret_cast<int>(&j) ;
r = reinterpret_cast<int>(&j) ;
|