2016-09-21 234 views
0

我正在學習C++中的指針和引用變量,並且我看到了一個示例代碼。我不確定爲什麼* c的值從33變爲22.有人能幫我理解這個過程嗎?爲什麼當我沒有給它賦值時變量的值會改變?

int a = 22; 
int b = 33; 
int* c = &a; //c is an int pointer pointing to the address of the variable 'a' 
int& d = b; //d is a reference variable referring to the value of b, which is 33. 
c = &b; //c, which is an int pointer and stored the address of 'a' now is assigned address of 'b' 
std::cout << "*c=" << *c << ", d=" << d << std::endl; //*c= 33 d= 33 
d = a; //d is a reference variable, so it cannot be reassigned ? 
std::cout << "*c=" << *c << ", d=" << d << std::endl; //*c= 33 d= 33 

回答

2
d = a; //d is a reference variable, so it cannot be reassigned ? 

這是一種誤解。該聲明將a(22)的值分配給d是對(b)的引用的變量。它確實改變了d的參考。因此,被執行的行之後,的b值是22。

+0

非常感謝! – Skipher

+0

@Skipher,不客氣。 –

2

讓我們通過步驟運行此片碼步驟的:

int a = 22; 
int b = 33; 

我們分配值,以A,B。不多說了。

int* c = &a; 

c保存a的地址。 * c是a的值,現在是22。

int& d = b; 

d是reference variable到b。從現在開始,d被視爲b的別名。 d的值也是b的值,即33。

c = &b; 

c現在保存着b的地址。 * c是b的值,現在是33。

d = a; 

我們將22(a的值)分配給d。由於d是b的別名,因此b現在也是22.因爲c指向b,* c是b的值,現在是22.

+0

謝謝你一步一步的過程! – Skipher

相關問題