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

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

    Formally speaking, that is impossible as it is forbidden by design. Arbitrarily speaking, that is possible.

    A references is stored as a pointer, so you can always change where it points to as long as you know how to get its address. Similarly, you can also change the value of const variables, const member variables or even private member variables when you don't have access to.

    For example, the following code has changed class A's const private member reference:

    #include 
    using namespace std;
    
    class A{
    private:
        const int &i1;
    public:
        A(int &a):i1(a){}
        int geti(){return i1;}
        int *getip(){return (int*)&i1;}
    };
    
    int main(int argc, char *argv[]){
        int i=5, j=10;
        A a(i);
        cout << "before change:" << endl;
        cout << "&a.i1=" << a.getip() << " &i=" << &i << " &j="<< &j << endl;
        cout << "i=" << i << " j=" <
                                                            
提交回复
热议问题