C++ 入門指南 - 介面與實作分開

所謂介面 (interface) 就是類別 (class) 宣告 (declare) 的部份,實作 (implementation) 則是成員函數 (member function) 定義的部份




C++ 的介面是放在標頭檔 (header file) 之中,我們為 Demo 類別設計一個 Demo.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Demo {
public:
    Demo();
    Demo(int n);
    Demo(int n1, int n2);
    void setA(int n);
    void setB(int n);
    int getA();
    int getB();
    int do_something();
 
private:
    int a;
    int b;
};
 
/* 《程式語言教學誌》的範例程式
    檔名:Demo.h
    功能:示範 C++ 程式
    作者:張凱慶
    時間:西元 2012 年 10 月 */


然後實作放在另一個 Demo.cpp 檔案中
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "Demo.h"
 
Demo::Demo() {
    a = 1;
    b = 1;
}
 
Demo::Demo(int n) {
    a = n;
    b = n;
}
 
Demo::Demo(int n1, int n2) {
    a = n1;
    b = n2;
}
 
int Demo::do_something() {
    return getA() + getB();
}
 
void Demo::setA(int n) {
    a = n;
}
 
void Demo::setB(int n) {
    b = n;
}
 
int Demo::getA() {
    return a;
}
 
int Demo::getB() {
    return b;
}
 
/* 《程式語言教學誌》的範例程式
    檔名:Demo.cpp
    功能:示範 C++ 程式
    作者:張凱慶
    時間:西元 2012 年 10 月 */


注意首行用雙引號引入 Demo.h ,角括弧用在標準程式庫 (standard library) ,至於自己設計的標頭檔則是用雙引號
1
#include "Demo.h"


Demo.cpp 並沒有 main() 函數 (function) ,因此我們需要另外設計一個包含 main() 的 .cpp 檔案
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
#include <iostream>
#include "Demo.h"
 
using namespace std;
 
int main(void) {
    Demo t1;
    Demo t2(11);
    Demo t3(11, 22);
  
    cout << endl;
    cout << t1.do_something() << endl;
    cout << t2.do_something() << endl;
    cout << t3.do_something() << endl;
    cout << endl;
     
    return 0;
}
 
/* 《程式語言教學誌》的範例程式
    檔名:classdemo4.cpp
    功能:示範 C++ 程式
    作者:張凱慶
    時間:西元 2012 年 10 月 */


classdemo4.cpp 同樣需要引入 Demo.h ,不然編譯器 (compiler) 會不認識 Demo 的名稱唷!


編譯時要把 Demo.cpp 與 classdemo4.cpp 放在一起編譯,編譯執行結果如下



C++ 的程式概念大抵介紹到這裡,接下來,我們要發展一個編密碼的 Encrypt 類別,藉以介紹更多 C++ 的特性。


中英文術語對照
介面interface
類別class
宣告declare
實作implementation
成員函數member function
標頭檔header file
標準程式庫standard library
函數function
編譯器compiler


您可以繼續參考
基礎篇


相關目錄
回 C++ 入門指南
回 C++ 教材目錄
回首頁


參考資料
http://www.cplusplus.com/doc/tutorial/classes/
http://www.cplusplus.com/doc/tutorial/classes2/

2 則留言:

j41k23 提到...

int main(void) {
Demo t1();
}

Q-Max 提到...

classdemo4.cpp那邊應該是#include "Demo.cpp"而不是Demo.h