
自訂函數的定義需要放在 main() 或呼叫之前,如果放在 main() 或呼叫之後,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | do_something("What's truth?"); |
| 005 | do_something("There is no spoon."); |
| 006 | |
| 007 | return 0; |
| 008 | } |
| 009 | |
| 010 | void do_something(char* s) { |
| 011 | std::cout << s |
| 012 | << std::endl; |
| 013 | } |
| 014 | |
| 015 | /* Kaiching Chang |
| 016 | u0801_1.cpp |
| 017 | 2014-02 */ |
這樣無法通過編譯
| $ g++ u0801_1.cpp |
| u0801_1.cpp:4:4: error: use of undeclared identifier 'do_something' |
| do_something("What's truth?"); |
| ^ |
| u0801_1.cpp:5:4: error: use of undeclared identifier 'do_something' |
| do_something("There is no spoon."); |
| ^ |
| 2 errors generated. |
| $ |
因為 C++ 預設任何識別字使用前都得先定義或宣告,如果我們要把自訂函數的定義放在 main() 或呼叫之後,就要先宣告函數原型 (function prototype) ,因此上例要改寫如下
| 001 | #include <iostream> |
| 002 | |
| 003 | void do_something(char*); |
| 004 | |
| 005 | int main() { |
| 006 | do_something("What's truth?"); |
| 007 | do_something("There is no spoon."); |
| 008 | |
| 009 | return 0; |
| 010 | } |
| 011 | |
| 012 | void do_something(char* s) { |
| 013 | std::cout << s |
| 014 | << std::endl; |
| 015 | } |
| 016 | |
| 017 | /* Kaiching Chang |
| 018 | u0801_2.cpp |
| 019 | 2014-02 */ |
函數原型的宣告在第 3 行
| 003 | void do_something(char*); |
參數列方面宣告參數的型態即可,編譯執行結果如下
| $ g++ u0801_2.cpp |
| $ ./a.out |
| What's truth? |
| There is no spoon. |
| $ |
通常函數原型的宣告會放在標頭檔 (header file) 之中,函數實作則會放在其他程式檔案。
continue ...
沒有留言:
張貼留言