Why can const int& bind to an int?

后端 未结 8 664
野性不改
野性不改 2021-02-04 04:39

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

8条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 04:58

    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.

提交回复
热议问题