Formally speaking, this is not possible, since it is prohibited by design. Generally speaking, this is possible.
Links are stored as a pointer, so you can always change where it points, as long as you know how to get its address. Similarly, you can also change the value of constant variables, constant member variables, or even private member variables when you do not have access.
For example, the following code changed the reference to class A const:
#include <iostream> 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=" <<j<< " a.i1=" << a.geti() << endl; i=6; cout << "setting i to 6" << endl; cout << "i=" << i << " j=" <<j<< " a.i1=" << a.geti() << endl; *(int**)&a = &j; // the key step that changes A member reference cout << endl << "after change:" << endl; cout << "&a.i1=" << a.getip() << " &i=" << &i << " &j="<< &j << endl; cout << "i=" << i << " j=" <<j<< " a.i1=" << a.geti() << endl; j=11; cout << "setting j to 11" << endl; cout << "i=" << i << " j=" <<j<< " a.i1=" << a.geti() << endl; return 0; }
Program output:
before change: &a.i1=0x7fff1b624140 &i=0x7fff1b624140 &j=0x7fff1b624150 i=5 j=10 a.i1=5 setting i to 6 i=6 j=10 a.i1=6 after change: &a.i1=0x7fff1b624150 &i=0x7fff1b624140 &j=0x7fff1b624150 i=6 j=10 a.i1=10 setting j to 11 i=6 j=11 a.i1=11
As you can see, a.i1 initially points to i, after changing it points to j.
However, this is considered dangerous and therefore not recommended, as it defeats the original goal of encapsulating data and OOP. This is more like a memory hack.
xuancong84 Sep 16 '15 at 10:57 2015-09-16 10:57
source share