In the C++ primer, I found that const int &
can bind with a int object.I don\'t understand that,because I think const int &
should bind with a
int a=0; const int &r=a; a=3; cout<
The output is that r=3; the value of r can be changed, why? I don't understand that.
The const
only applies to the reference r
. It means that you can't change whatever r
binded to via r
. You can't do:
r = 3;
That will be an error, because r
is a const int&
and cannot be modified. For now you can think of references as some sort of lightweight transparent "proxy" of an object. So if the "proxy" is const
, you cannot modify the object through the "proxy". However, it doesn't mean the original object cannot be modified.