簡體   English   中英

當我沒有給變量賦值時,為什么變量的值會改變?

[英]Why is the value of a variable changed when I did not assign a new value to it?

我正在學習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
 d = a; //d is a reference variable, so it cannot be reassigned ? 

那是個誤會。 該語句將a (22)的值分配給變量d ,該變量d是對( b )的引用。 確實會改變d的引用。 因此,在執行該行之后, b值為22。

讓我們逐步運行這段代碼:

int a = 22;
int b = 33;

我們將值分配給a,b。 沒什么好說的。

int* c = &a;

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

int& d = b;

d是b的參考變量 從現在開始,d被視為b的別名 d的值也是b的值,即33。

c = &b;

c現在擁有b的地址。 * c是b的值,現在為33。

d = a;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM