
如果有需要用函數直接修改某些變數,就可以設計接收參考參數 (reference parameter) 的函數,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | void do_something(int& n_ref) { |
| 004 | n_ref = 10; |
| 005 | } |
| 006 | |
| 007 | int main() { |
| 008 | int a = 22; |
| 009 | std::cout << a |
| 010 | << std::endl; |
| 011 | |
| 012 | do_something(a); |
| 013 | std::cout << a |
| 014 | << std::endl; |
| 015 | |
| 016 | return 0; |
| 017 | } |
| 018 | |
| 019 | /* Kaiching Chang |
| 020 | u0803_1.cpp |
| 021 | 2014-02 */ |
do_something() 接受一個整數參考參數,然後將參數重新設定為 10
| 003 | void do_something(int& n_ref) { |
| 004 | n_ref = 10; |
| 005 | } |
編譯執行,結果如下
| $ g++ u0803_1.cpp |
| $ ./a.out |
| 22 |
| 10 |
| $ |
由於函數只能有一個回傳值,因此當程式中有多個變數需要用函數修改時,利用參考當參數為一個解決方案,另舉一例如下
| 001 | #include <iostream> |
| 002 | |
| 003 | int do_something2 |
| 004 | (int &n1_ref, int &n2_ref) { |
| 005 | n1_ref *= 2; |
| 006 | n2_ref *= 2; |
| 007 | |
| 008 | return n1_ref + n2_ref; |
| 009 | } |
| 010 | |
| 011 | int main() { |
| 012 | int a = 22; |
| 013 | int b = 33; |
| 014 | std::cout << "a + b: " |
| 015 | << do_something2(a, b) |
| 016 | << std::endl; |
| 017 | std::cout << "a: " |
| 018 | << a |
| 019 | << std::endl; |
| 020 | std::cout << "b: " |
| 021 | << b |
| 022 | << std::endl; |
| 023 | |
| 024 | return 0; |
| 025 | } |
| 026 | |
| 027 | /* Kaiching Chang |
| 028 | u0803_2.cpp |
| 029 | 2014-02 */ |
編譯執行,結果如下
| $ g++ u0803_2.cpp |
| $ ./a.out |
| a + b: 110 |
| a: 44 |
| b: 66 |
| $ |
continue ...
沒有留言:
張貼留言