
前置處理器指令 #include 用來引入標頭檔 (header file) ,例如引入標準程式庫 (standard library) 的功能
| 001 | #include <iostream> |
| 002 | #include <string> |
| 003 | |
| 004 | int main() { |
| 005 | std::string s = "There is no spoon."; |
| 006 | std::cout << s.find("no") |
| 007 | << std::endl; |
| 008 | |
| 009 | return 0; |
| 010 | } |
| 011 | |
| 012 | /* Kaiching Chang |
| 013 | u1403_1.cpp |
| 014 | 2014-02 */ |
這裡 iostream 與 string 都是標準程式庫的標頭檔,引入標準程式庫的標頭檔要放在角括號中,也就是大於、小於的符號內
| 001 | #include <iostream> |
| 002 | #include <string> |
由於標準程式庫中的識別字都定義在 std 命名空間中,因此使用標準程式庫的識別字需要加上 std::
| 005 | std::string s = "There is no spoon."; |
可以先用 using namespace std; 省略程式中大量的 std:: 。
string 為標準程式庫中定義的字串物件,這裡使用字串物件的 find() 成員函數找到子字串第一次出現的索引值
| 006 | std::cout << s.find("no") |
編譯執行,結果如下
| $ g++ u1403_1.cpp |
| $ ./a.out |
| 9 |
| $ |
除了引入標準程式庫的標頭檔外, #include 也用來引入自行定義的標頭檔,通常會把類別、常數、函數原型宣告放在自行定義的標頭檔中,例如我們有以下的標頭檔
| 001 | class Demo { |
| 002 | public: |
| 003 | int a; |
| 004 | int b; |
| 005 | |
| 006 | int do_something(); |
| 007 | }; |
| 008 | |
| 009 | /* Kaiching Chang |
| 010 | u1403_2.h |
| 011 | 2014-02 */ |
標頭檔為副檔名為 .h 的檔案。
我們用以下的程式引入 u1403_2.h
| 001 | #include <iostream> |
| 002 | #include "u1403_2.h" |
| 003 | |
| 004 | int Demo::do_something() { |
| 005 | return a + b; |
| 006 | } |
| 007 | |
| 008 | int main() { |
| 009 | Demo d; |
| 010 | d.a = 1; |
| 011 | d.b = 2; |
| 012 | std::cout << d.do_something() |
| 013 | << std::endl; |
| 014 | |
| 015 | return 0; |
| 016 | } |
| 017 | |
| 018 | /* Kaiching Chang |
| 019 | u1403_2.cpp |
| 020 | 2014-02 */ |
引入自行定義的標頭檔使用雙引號
| 002 | #include "u1403_2.h" |
實作也會放在獨立的 .cpp 程式檔案
| 004 | int Demo::do_something() { |
| 005 | return a + b; |
| 006 | } |
編譯執行,結果如下
| $ g++ u1403_2.cpp |
| $ ./a.out |
| 3 |
| $ |
continue ...
沒有留言:
張貼留言