1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> int main( void ) { do_something( "What's truth?" ); do_something( "There is no spoon." ); return 0; } void do_something( char *s) { std::cout << s << std::endl; } /* 《程式語言教學誌》的範例程式 檔名:fundemo13.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
這樣無法通過編譯

因為 C++ 預設任何識別字 (identifier) 使用前都得先定義或宣告,如果我們要把自訂函數的定義放在 main() 或呼叫之後,就要先宣告函數原型 (function prototype) ,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> void do_something( char *); int main( void ) { do_something( "What's truth?" ); do_something( "There is no spoon." ); return 0; } void do_something( char *s) { std::cout << s << std::endl; } /* 《程式語言教學誌》的範例程式 檔名:fundemo14.cpp 功能:示範 C++ 程式 作者:張凱慶 時間:西元 2013 年 1 月 */ |
函數原型的宣告在第 3 行
3 | void do_something( char *); |
參數列方面宣告參數的型態 (type) 即可,編譯執行結果如下

通常函數原型的宣告會放在標頭檔 (header file) 之中,函數實作則會放在其他程式檔案。
中英文術語對照 | |
---|---|
函數 | function |
識別字 | identifier |
函數原型 | function prototype |
型態 | type |
標頭檔 | header file |
您可以繼續參考
函數
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
沒有留言:
張貼留言