1 int rats=101; 2 int & rodents=rats;
注意:引用一旦被建立不能更改其與某個變量之間的關係,即引用不能再表明其餘變量。程序員
注(什麼是左值?):左值參數是可被引用的數據對象,例如變量、數組元素、結構成員、引用和解除引用的指針都是左值。非左值包括字面常量(用引號括起的字符串除外,他們由其地址表示)和包含多項的表達式。編程
使用 const 引用使函數可以正確生成並使用臨時變量。數組
避免返回函數終止時不在存在的內存單元引用,解決辦法:函數
1 free_throws & clone(free_throws & ft) 2 { 3 ... 4 return ft; 5 } 6 7 clone(ft)=four; //it's allowed, four covered ft
const free_throws & clone(free_throws & ft) { ... return ft; } clone(ft)=four; //it's not allowed
display(clone(ft)); //it's allowed, you can ues it like this
void file_it(ostream & os) { ... } ofstream fout; file_it(fout);
例如:參數 os (其類型爲 ostream & )能夠指向 ostream 對象(如 cout ),也能夠指向 ofstream 對象(如 fout )。this