我们知道,引用在初始化后,不能再被重新声明为另一个变量的引用,比如:
int i, j; int &k = i; k = &j; //这是错误的
但是我们可以改变引用所指向的变量的值,比如
int i, j; int &k = i; k = j;
注意,这里k = j,修改的是k的值
接下来我们看这样一个例子加深理解:
#include <iostream> using namespace std; int main() { int i = 5, j = 10; int &k = i; cout << "i = " << i << "\t&i = " << &i << endl; cout << "j = " << j << "\t&j = " << &j << endl; cout << "k = " << k << "\t&k = " << &k << endl; }
输出的结果为:
i = 5 &i = 0x6afef8 j = 10 &j = 0x6afef4 k = 5 &k = 0x6afef8
可以看到,通过为变量i起别名k后,引用k的地址已经和变量i的地址完全相同
接下来,我们再来添加下面的这行代码:
k = j;
再来看一下i,j,k的值和地址:
#include <iostream> using namespace std; int main() { int i = 5, j = 10; int &k = i; cout << "i = " << i << "\t&i = " << &i << endl; cout << "j = " << j << "\t&j = " << &j << endl; cout << "k = " << k << "\t&k = " << &k << endl; k = j; cout << "**************k = j后***************** " << endl; cout << "i = " << i << "\t&i = " << &i << endl; cout << "j = " << j << "\t&j = " << &j << endl; cout << "k = " << k << "\t&k = " << &k << endl; }
结果是:
i = 5 &i = 0x6afef8 j = 10 &j = 0x6afef4 k = 5 &k = 0x6afef8 **************k = j后***************** i = 10 &i = 0x6afef8 j = 10 &j = 0x6afef4 k = 10 &k = 0x6afef8
可以看到,i和k的地址虽然没有改变,但是值却都变成了10,也就是k -= j这个操作,只是把j的值赋给了k而已,并没有修改k的地址
请登录之后再进行评论