1. 程式人生 > 其它 >【C++學習】引用變數

【C++學習】引用變數

1. 引用變數必須在宣告時初始化,且之後無法更改(更改指的是成為其他變數的引用,即:引用變數一旦與某個變數關聯起來,就一直效忠於它)

類似於const 指標:

int a = 10;
int & re = a;  //re的引用不可變
int * const pr = &a; // pr的指向不可變 
 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int a = 101;
 7     int b = 50;
 8     int & re = a;
 9
cout << "a value: " << a << endl; 10 cout << "a address: " << &a << endl; 11 cout << "b value: " << b << endl; 12 cout << "b address: " << &b << endl; 13 cout << "re value: " << re << endl;
14 cout << "re address: " << &re << endl; 15 re = b; //這裡只是將b的值賦值給re引用的變數(a),無法讓re引用新的變數(b) 16 cout << "a value: " << a << endl; 17 cout << "a address: " << &a << endl; 18 cout << "b value: " << b << endl;
19 cout << "b address: " << &b << endl; 20 cout << "re value: " << re << endl; 21 cout << "re address: " << &re << endl; 22 return 0; 23 } 24 /* 25 輸出 26 a value: 101 27 a address: 0x6dfee8 28 b value: 50 29 b address: 0x6dfee4 30 re value: 101 31 re address: 0x6dfee8 32 a value: 50 33 a address: 0x6dfee8 34 b value: 50 35 b address: 0x6dfee4 36 re value: 50 37 re address: 0x6dfee8 38 */
例1
 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int a = 101;
 7     int * pt = &a;
 8     int & re = *pt;
 9     cout << "pt: " << pt << endl;
10     cout << "re: " << &re << endl;
11     cout << "a: " << &a << endl;
12     int b = 50;
13     pt = &b;  // pt指向b, 但是re仍然是a的引用
14     cout << "pt: " << pt << endl;
15     cout << "re: " << &re << endl;
16     cout << "a: " << &a << endl;
17     cout << "b:" << &b << endl;
18     return 0;
19 }
20 
21 /*
22 輸出
23 pt: 0x6dfee4
24 re: 0x6dfee4
25 a: 0x6dfee4
26 pt: 0x6dfee0
27 re: 0x6dfee4
28 a: 0x6dfee4
29 b:0x6dfee0
30 */
例2