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

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

    You can't reassign a reference, but if you're looking for something that would provide similar abilities to this you can do a pointer instead.

    int a = 2;
    int b = 4;
    int* ptr = &a;  //ptr points to memory location of a.
    ptr = &b;       //ptr points to memory location of b now.
    

    You can get or set the value within pointer with: 

    *ptr = 5;     //set
    int c = *ptr; //get
    

提交回复
热议问题