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

前端 未结 10 1025
既然无缘
既然无缘 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:17

    That's not possible in the way you want. C++ just doesn't let you rebind what a reference points to.

    However if you want to use trickery you can almost simulate it with a new scope (NEVER do this in a real program):

    int a = 2;
    int b = 4;
    int &ref = a;
    
    {
        int& ref = b; // Shadows the original ref so everything inside this { } refers to `ref` as `b` now.
    }
    

提交回复
热议问题