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
don't understand that,because I think
const int &
should bind with aconst int
not aint
object
You are mistaken. A reference-to-const (const reference in short) doesn't mean that only const objects can be bound. It means that the object can not be modified through the reference.
What is not allowed would be to bind a non-const reference to a const object, because such reference could be used to modify the object which would break the constness.
the value of
r
can be changed, why?
The object that r
refers to was modified - which is OK because the object isn't const. r
still refers to the same object and the object was not modified using r
.
Having a const reference does not mean that the referred object can not change. It means that the object can not be changed using that reference.
If you wish to have an object that can not change, then that object itself has to be const. A const reference does not make the referred object const. The book has shown you how to create a const object:
const int b=a;
I have regarded reference as poiter mistakely,because they are similiar some time.
Indeed, references are very similar to pointers. Regarding the context of this question, they behave similarly. A demo:
int a=0;
const int *r=&a;
a=3;
cout<<*r<