簡體   English   中英

為什么在C ++入門5中,引用被認為沒有改變,以下代碼如何工作?

[英]Why a reference is said to be unchanged in C++ primer 5th, how ever this following code works?

在本書中,我們解釋說沒有辦法讓引用引用不同的對象,以下代碼如何適用於c ++ 11。

int i1 = 1, i2 = 0;
int &ri = i1;
ri = i2;

ri並沒有改變它所指向的東西,它改變了它所指向的價值。 因此,如果您打印i1的值,您將看到它現在等於0 ,如果您更改i2的值,您將看到它不會影響ri

int main() {
    int i1 = 1, i2 = 0;
    int& ri = i1;
    ri = i2; // i1 == 0
    std::cout << "i1 " << i1 << "\n";
    i2 = 5;
    std::cout << "i2 " << i2 << "\n";
}

輸出是

i1 0
i2 5

為什么在C ++入門5中,引用被認為沒有改變,以下代碼如何工作?

因為可以更改整數的值。 這就是ri = i2作用。 參考不受影響; 它仍然指的是同一個對象。 引用對象的值受到影響。 結果就像你寫了i1 = i2

為了更好地理解,請嘗試以下方法:

int i1 = 1, i2 = 0;

int &ri = i1;          // ri refers to i1 and this won't change afterwards
cout << ri <<endl;     // same value as i1, so 1
i1 = 3; 
cout << ri <<endl;     // still same value as i1, but now it's 3
ri = 5; 
cout << i1 <<endl;     // same value as ri since both name refer to the same variable, so 5

ri = i2;               // ri still refers to i1, but copies value of i2 in it
cout << i1<<endl;      // i1 was overwritten through ri
ri = 7;  
cout << i1 << endl     // i1 was overwritten again through ri
     <<i2 <<endl;      // but i2 stays unchanged, since ri does not refer to it.  

暫無
暫無

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

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