int &ref = x; 讓 ref 成為 x 的別名,操作 ref 等同操作 x 本身,不產生新記憶體。這與指標 int *ptr = &x; 在語義上不同:參考不能為 null、不可重新綁定、語法更直觀。
// 1. 傳值:複製副本,函數內修改不影響外部
int CalPfh1(int x, int y) { return x*x + y*y; }
// 2. 傳指標:傳遞位址,需解參考,可為 null
void CalPfh2_ptr(int x, int y, int *z) { *z = x*x + y*y; }
// 3. 參考參數:語法如傳值,效果如傳址,最推薦用於輸出參數
void CalPfh2_ref(int x, int y, int &z) { z = x*x + y*y; }
int z = 0;
cout << CalPfh1(3, 2) << endl; // 輸出 13
CalPfh2_ref(3, 2, z);
cout << z; // 輸出 13
bool TryParse(string, out int) 模式)void func(const BigObject &obj) 加上 const 保證不修改ostream& operator<<(ostream&, const T&)「參考比指標快」——錯誤。編譯器通常將參考實作為指標,效能相同。參考的優勢在語法安全性與可讀性。