我有一个指向整数变量的指针。然后我将此指针指定给引用变量。现在,当我将指针更改为指向其他整数变量时,引用变量的值不会更改。任何人都可以解释原因吗?
int rats = 101;
int * pt = &rats;
int & rodents = *pt; // outputs
cout << "rats = " << rats; // 101
cout << ", *pt = " << *pt; // 101
cout << ", rodents = " << rodents << endl; // 101
cout << "rats address = " << &rats; // 0027f940
cout << ", rodents address = " << &rodents << endl; // 0027f940
int bunnies = 50;
pt = &bunnies;
cout << "bunnies = " << bunnies; // 50
cout << ", rats = " << rats; // 101
cout << ", *pt = " << *pt; // 50
cout << ", rodents = " << rodents << endl; // 101
cout << "bunnies address = " << &bunnies; // 0027f91c
cout << ", rodents address = " << &rodents << endl; // 0027f940
我们将pt分配给兔子,但是啮齿动物的价值仍然是101.请解释原因。
答案 0 :(得分:2)
该行
int & rodents = *pt;
正在创建对pt
指向的内容的引用(即rats
)。它不是指针pt
的引用。
稍后,当您指定pt
指向bunnies
时,您不希望rodents
引用更改。
编辑:为了说明@Als点,请考虑以下代码:
int value1 = 10;
int value2 = 20;
int& reference = value1;
cout << reference << endl; // Prints 10
reference = value2; // Doesn't do what you might think
cout << reference << endl; // Prints 20
cout << value1 << endl; // Also prints 20
第二个reference
作业不更改引用自身。相反,它将赋值运算符(=
)应用于引用的事物,即value1
。
reference
将始终引用value1
并且无法更改。
首先让你头脑发热有点棘手,所以我建议你看看Scott Meyer的优秀书籍Effective C++和More Effective C++。他比我能更好地解释这一切。