防止同一個頭文件被包含多次而導致重復定義。
舉個例子:如果沒有防衛(wèi)式聲明
// 頭文件 A.h
class A{};
// 頭文件 B.h
#include "A"
using namespace std;
class B{};
// main.cpp
#include "A"
#include "B"
using namespace std;
int main()
{
? ? B b;
????reutrn 0;
}
編譯出錯,Redefination of 'A'
為什么會出現(xiàn)這樣的情況??
在編譯階段,編譯器會把頭文件展開。此時main.cpp中的代碼如下:
class A{};
calss A{};
class B{};
int main()
{
? ? B b;
? ? return 0;
}