用 C++ 開發中大型專案時,檔案怎麼擺放會直接影響可維護性。最簡單的原則是:標頭檔(.h)放「類別的宣告」,包含資料成員與函式成員;實作檔(.cpp)放「成員函式的定義」。這樣一來,介面與實作分離,改動實作時不必重新編譯所有依賴的檔案。
假設我們用 C++ 寫了一個二元樹類別,類別定義放在 BinaryTree.h:
#pragma once
#include "iostream"
using namespace std;
struct Node
{
char data;
Node *l;
Node *r;
};
class BinaryTree
{
int level;
int node_num;
int array_len;
Node *temp[100];
public:
Node *root;
BinaryTree(void);
~BinaryTree(void);
void count_node();
void pre_order_bitree(Node *N);
void in_order_bitree(Node *N);
void post_order_bitree(Node *N);
};
接著在 .cpp 中先引入 #include "BinaryTree.h",主體內容就是成員函式的實作。以前序遍歷為例:
void BinaryTree::pre_order_bitree(Node *N)
{
if (N != NULL)
{
cout << N->data;
pre_order_bitree(N->l);
pre_order_bitree(N->r);
}
}
而主程式只要把標頭檔包進來就能使用這個類別:
#include "StdAfx.h"
#include "BinaryTree.h"
int main()
{
BinaryTree biTree; // 呼叫建構子
biTree.count_node();
cout << "先序遍歷是:" << endl;
biTree.pre_order_bitree(biTree.root);
return 1;
}
#pragma once 的作用是避免同一個標頭檔被重複引入,在跨平台專案裡也可以改用傳統的 include guard 達到相同效果。