c++入門 (頭文件)

Definition of a class      類的定義
1. In C++,seperated .h and .cpp file are used to define on class.  C++用.h 和 .cpp文件來分別定義類
2. Class declaration and prototypes in that class are in the header file.(.h)   類的聲明和原型在.h文件內

3. All the bodies of these functions are in the source file(.cpp).       方法的實現在.cpp文件內

The header files   關於頭文件
If a function is declared in a header file,you must include the header file everywhere the function is used and where the function is defined.
如果一個方法在頭文件中聲明,你必須在使用該方法的地方包含這個頭文件。


If a class is declared in a header fike,you must include the header file everywhere the class is used and where class member function are defined.

如果一個類在頭文件中聲明,你必須在使用該方法的地方包含這個頭文件。


Header = interface 頭文件等同於接口
The header is a contract between you and the user of your code.  頭文件是你和你的代碼的使用者之間的約定
The compile enforces the contract by requiring you to declare all structures and functions before they are used. 編譯器強制執行這個約定,使用方法之前必須聲明。


頭文件的包含指令以#開頭,是編譯預處理指令,編譯器,會將整個.h文件,插入到include的位置

#include is to insert the included file into the .cpp file at where t he #include statement is.

#include "xx.h" :first search in the current directory, then the  directories declared somewhere. 先在當前目錄找,再在指定目錄找

#include <xx.h>:search in the specified directories.  在指定目錄查找: unix/linux 是/usr/include.  windows 則是在安裝的編譯器指定的位置,沒有系統統一的位置

#include<xx> same as #include<xx.h>

g++ a.cpp --save-temps          vi a.ii  可以看到包含的文件已經插入到include的位置。


Declarations vs. Definitions.   聲明 vs. 定義
A .cpp file is a compile unit.     一個cpp文件是一個編譯單元
Only declarations are allowed to be in .h      .h文件中只能包含聲明
extern variables
function prototypes
class/struct declaration


Standard header file structure  標準頭文件結構,用於解決a.h包含b.h,反過來b.h又包含a.h的問題。
#ifndef HEADER_FLAG
#define HEADER_FLAG
//Type declaration here..
#endif



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章