[英]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.