Modifying reference member from const member function in C++

后端 未结 3 1106
走了就别回头了
走了就别回头了 2020-12-06 03:57

I am working on const-correctness of my code and just wondered why this code compiles:

class X
{
    int x;
    int& y;
public:
    X(int& _y):y(_y)
         


        
3条回答
  •  自闭症患者
    2020-12-06 05:02

    Because you are not changing any variable in X. Actually, you are changing _y which is an outsider with respect to your class. Don't forget that:

    y = newY;
    

    Is assigning the value of newY to the variable pointed by y, but not the references them selves. Only on initialization the references are considered.

提交回复
热议问题