How can I change the variable to which a C++ reference refers?

前端 未结 10 1026
既然无缘
既然无缘 2020-11-29 01:50

If I have this:

int a = 2;
int b = 4;
int &ref = a;

How can I make ref refer to b after this code?

10条回答
  •  粉色の甜心
    2020-11-29 02:30

    Although its a bad idea as it defeats the purpose of using references, it is possible to change the reference directly

    const_cast< int& >(ref)=b;
    

提交回复
热议问题