1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> void do_something( int n1, int n2, int n3) { std::cout << n1 + n2 + n3 << std::endl; } void do_something( double n1, double n2, double n3) { std::cout << n1 + n2 + n3 << std::endl; } void do_something( int n1) { std::cout << n1 << std::endl; } int main( void ) { do_something(10); do_something(0.2, 4.5, 6.1); do_something(3, 4, 5); return 0; } /* 《程式語言教學誌》的範例程式 檔名:fundemo16.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
這裡定義了三個 do_something() 函數,有三種參數版本,第一個版本需要三個整數參數
3 | void do_something( int n1, int n2, int n3) { |
第二個版本需要一個浮點數參數與兩個整數參數
7 | void do_something( double n1, double n2, double n3) { |
第三個版本則只需要一個整數參數
11 | void do_something( int n1) { |
不同的參數版本使相同名稱的函數能夠處理不同的資料型態 (data type) ,此例編譯執行結果如下

中英文術語對照 | |
---|---|
函數 | function |
參數 | parameter |
重載 | overload |
資料型態 | data type |
您可以繼續參考
函數
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
沒有留言:
張貼留言