const int a = 0; // a 為整數常數 const int &aRef = a; // aRef 為 a 的常數參考 |
假如不是用常數參考指向 const 常數,就會發生編譯錯誤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> int main( void ) { const int a = 0; int &aRef = a; std::cout << aRef << std::endl; return 0; } /* 《程式語言教學誌》的範例程式 檔名:constdemo3.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
此例不是用常數參考指向 const 常數
6 | int &aRef = a; |
編譯器會給予錯誤訊息

這是因為 const int 就必須用 const int& 的參考變數。
反倒常數參考可指向任意變數,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> int main( void ) { int a = 0; const int &aRef = a; a = 22; std::cout << aRef << std::endl; return 0; } /* 《程式語言教學誌》的範例程式 檔名:constdemo4.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
編譯執行結果如下

這是因為 a 並非 const 的。
中英文術語對照 | |
---|---|
常數參考 | const reference |
參考 | reference |
別名 | alias |
您可以繼續參考
常數 const
同義字 typedef
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
沒有留言:
張貼留言