1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> void do_something( int n = 22) { std::cout << n << std::endl; } int main( void ) { do_something(11); do_something(); do_something(); return 0; } /* 《程式語言教學誌》的範例程式 檔名:fundemo09.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
參數 n 的預設值為 22
3 | void do_something( int n = 22) { |
這樣不使用參數也可以呼叫 (call)
9 10 11 | do_something(11); do_something(); do_something(); |
編譯執行結果如下

預設參數可以是選擇性的,也就是可以替特定參數設定預設值,其他參數則須呼叫時填入小括弧,需要注意這樣的預設參數必須放在參數列的後面,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> void do_something2( int n1, int n2 = 5, int n3 = 0) { std::cout << n1 + n2 + n3 << std::endl; } int main( void ) { do_something2(6); do_something2(6, 9); do_something2(3, 4, 5); return 0; } /* 《程式語言教學誌》的範例程式 檔名:fundemo10.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
留意 n1 並沒有預設值
3 | void do_something2( int n1, int n2 = 5, int n3 = 0) { |
因此呼叫時至少要有一個參數
9 10 11 | do_something2(6); do_something2(6, 9); do_something2(3, 4, 5); |
編譯執行結果如下

注意參數列 (parameter list) 的順序,像是下面就無法通過編譯
3 | void do_something2( int n1 = 6, int n2, int n3 = 0) { |
中英文術語對照 | |
---|---|
函數 | function |
預設參數 | default parameter |
參數 | parameter |
呼叫 | call |
您可以繼續參考
函數
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
沒有留言:
張貼留言