1
我有一個指向一個整數變量的指針。然後我將這個指針分配給一個引用變量。現在當我改變指針指向其他整數變量時,引用變量的值不會改變。誰能解釋爲什麼?參考變量和指針問題
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.請解釋原因。
所以你的意思是說,如果齧齒動物被分配給一個變量,那麼它不能再引用任何其他變量。 – Naphstor
@Naphstor:是的,你是正確的。引用不能綁定引用任何其他變量,它們總是保持對它們綁定到的變量的引用。 –