引用的類型必須與其所引用對象的類型一致.可是,對const的引用是第一種例外狀況.ios
對const的引用,常簡稱爲"常量引用". 常量引用的初始值能夠是任意表達式,只要該表達式的結果能轉換成引用的類型便可.測試
可是,對於字面值,通常表達式以及與常量引用類型不一致的對象做爲常量引用的初始值,常量引用實際綁定到了臨時變量上.測試代碼以下:spa
1 #include <iostream>
2
3 int main() 4 { 5 int i = 42; 6 int &r1 = i; 7
8 const int &r2 = i; 9 std::cout << "r2 = " << r2 << std::endl; 10 r1 = 40; 11 std::cout << "r2 = " << r2 << std::endl;//測試r2是否改變.
12
13 const int &r3 = i * 2; 14 std::cout << "r3 = " << r3 << std::endl; 15 r1 = 30; 16 std::cout << "r3 = " << r3 << " i = " << i << std::endl;//測試r3是否改變.
17
18 std::cout << "Double===========================" << std::endl;//測試r3是否改變.
19
20 double val = 3.14; 21 const int &r4 = val; 22 std::cout << "r4 = " << r4 << std::endl; 23 val = 5.2; 24 std::cout << "r4 = " << r4 << " val = " << val << std::endl;//測試r4是否改變.
25
26
27 double val_2 = 2.1; 28 const double &r5 = val_2 * 2; 29 std::cout << "r5 = " << r5 << std::endl; 30 val_2 = 9.35; 31 std::cout << "r5 = " << r5 << " val_2 = " << val_2 << std::endl;//測試r5是否改變.
32
33
34
35 const int val_3 = 3; 36 const double &r6 = val_3; 37 std::cout << "r6 = " << r6 << " val_3 = " << val_3 << std::endl;//測試r6是否改變.
38
39 return 0; 40 }
運行結果以下:code
能夠看出對於通常表達式,常量引用綁定到臨時變量上.對於上述最後一種狀況,分析r6也只能綁定到臨時量上.對象
最後總結一下.常量引用只有2種狀況會綁定到實際的對象:一是常量引用的初始值爲const對象,且該對象類型與常量引用類型相同(如const int i ; const int &r = i;);二是常量引用的初始值爲非const對象,且該對象也與常量引用類型(除去const的類型)相同(如int i; const int &r = i;).測試代碼中,r2的狀況便是如此.這種狀況下,綁定的非const對象內容能夠用其餘普通引用改變. blog