歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用C++開發工程時項目的管理: .h和.cpp文件的存放

用C++開發工程時項目的管理: .h和.cpp文件的存放

日期:2017/3/1 9:48:04   编辑:Linux編程

在用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; //call the construct-function
biTree.count_node();
cout<<"先序遍歷是:"<<endl;
biTree.pre_order_bitree(biTree.root);
return 1;
}

Copyright © Linux教程網 All Rights Reserved