Why can const int& bind to an int?

后端 未结 8 574
野性不改
野性不改 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:48

    There are two things: Const and reference.

    Reference is just another name for same memory unit. You can use any name to change the value held at that memory.

    A const reference is denoted in C++ by a code like

    int j =2; 
    int const &i = j; //or Alternatively
    const int &i = j;
    

    There is no restriction which makes the referred object to be constant as well.

    Here, you can not use i to change value of j. However this does not make the memory location j to be constant.You can peacefully change the value of j.

    j =3
    //but i = 3 will raise an error saying 
    //assignment of read-only reference ‘i’
    

提交回复
热议问题