
參考是變數 (variable) 的別名 (alias) ,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | int a = 22; |
| 005 | int& a_ref = a; |
| 006 | |
| 007 | std::cout << "a: " |
| 008 | << a |
| 009 | << std::endl; |
| 010 | std::cout << "a_ref: " |
| 011 | << a_ref |
| 012 | << std::endl; |
| 013 | |
| 014 | a_ref = 11; |
| 015 | std::cout << "a: " |
| 016 | << a |
| 017 | << std::endl; |
| 018 | std::cout << "a_ref: " |
| 019 | << a_ref |
| 020 | << std::endl; |
| 021 | |
| 022 | return 0; |
| 023 | } |
| 024 | |
| 025 | /* Kaiching Chang |
| 026 | u0701_1.cpp |
| 027 | 2014-02 */ |
第 5 行,宣告參考的型態 (type) 必須與參考所指向的變數型態相同,然後在型態名稱後後使用 & 運算子 (operator) 標明這是個參考變數,因此這個例子的參考變數為 a_ref ,等號右邊為所要指向的變數,此例為 a
| 005 | int& a_ref = a; |
由於 C++ 是自由格式的程式語言,因此寫成 int & a_ref 或 int &a_ref 都可以。
接下來我們印出 a 與 a_ref 的值,然後把 a_ref 改成 11
| 014 | a_ref = 11; |
這樣 a 也會變成 11 ,編譯後執行結果如下
| $ g++ u0701_1.cpp |
| $ ./a.out |
| a: 22 |
| a_ref: 22 |
| a: 11 |
| a_ref: 11 |
| $ |
由上可看出參考等同於原來的變數,這被稱為左值參考 (lvalue reference) 。 C++11 增加了一個右值參考 (rvalue reference) ,用以增進運算的效率,這是用 && 來宣告,例如
| int&& ref = a + b + c; |
右值參考是對運算式的參考,舉例如下
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | int a = 22; |
| 005 | int b = 33; |
| 006 | int c = 11; |
| 007 | int&& ref = a + b + c; |
| 008 | |
| 009 | std::cout << "a: " |
| 010 | << a |
| 011 | << std::endl; |
| 012 | std::cout << "b: " |
| 013 | << b |
| 014 | << std::endl; |
| 015 | std::cout << "c: " |
| 016 | << c |
| 017 | << std::endl; |
| 018 | std::cout << "ref: " |
| 019 | << ref |
| 020 | << std::endl; |
| 021 | |
| 022 | ref += 66; |
| 023 | std::cout << "a: " |
| 024 | << a |
| 025 | << std::endl; |
| 026 | std::cout << "b: " |
| 027 | << b |
| 028 | << std::endl; |
| 029 | std::cout << "c: " |
| 030 | << c |
| 031 | << std::endl; |
| 032 | std::cout << "ref: " |
| 033 | << ref |
| 034 | << std::endl; |
| 035 | |
| 036 | return 0; |
| 037 | } |
| 038 | |
| 039 | /* Kaiching Chang |
| 040 | u0701_2.cpp |
| 041 | 2014-02 */ |
編譯後執行,結果如下
| $ g++ u0701_2.cpp -std=c++0x |
| $ ./a.out |
| a: 22 |
| b: 33 |
| c: 11 |
| ref: 66 |
| a: 22 |
| b: 33 |
| c: 11 |
| ref: 132 |
| $ |
continue ...
沒有留言:
張貼留言