常見錯誤用法
------------------------a.h---------------------
#ifndef header_aaa
#define header_aaa
#include "b.h"
class a ;
#endif
--------------------------a.cpp-----------------
#include "a.h"
a::a(void)
a::~a(void)
---------------------------b.h---------------------
#ifndef header_bbb
#define header_bbb
#include "a.h"
class b ;
#endif
--------------------------b.cpp-----------------
#include "b.h"
b::b(void)
b::~b(void)
a b::func(a g)
經過vc編譯發現,編譯始終不過,error c2146: 語法錯誤 : 缺少「;」
原因:在預編譯時,出現迴圈巢狀。(.h檔案在cpp檔案中替換)
比如在編譯-a.cpp時的情況:
-----------a.cpp---------
#include "a.h" 替換
-------------------------
#ifndef header_aaa
#define header_aaa
-1111111111111111111111-
------------------------
#include "b.h" 替換
------------------------
#ifndef header_bbb
#define header_bbb
-222222222222222222222222-
------------------------
#include "a.h"
------------------------
#ifndef header_aaa
#define header_aaa
-------------------------
#include "b.h"--------迴圈。。。。
class a ;
#endif
-22222222222222222222222-
class b ;
#endif
-1111111111111111111111-
class a ;
#endif
正確用法:使用前置class x;
-----------------------a.h---------------------
#ifndef header_aaa
#define header_aaa
#include "b.h"
class a ;
#endif
--------------------------a.cpp-----------------
#include "a.h"
a::a(void)
a::~a(void)
---------------------------b.h---------------------
#ifndef header_bbb
#define header_bbb
class a;
class b ;
#endif
--------------------------b.cpp-----------------
#include "a.h"
#include "b.h"
b::b(void)
b::~b(void)
a b::func(a g)
比如在編譯
-a.cpp時的情況:
#ifndef header_aaa
#define header_aaa
----------begin1-------
#include "b.h" --替換
---------------------
#ifndef header_bbb
#define header_bbb
class a;
class b ;
#endif
--------end1----------
class a ;
#endif
比如在編譯
-b.cpp時的情況:
--------------------------b.cpp-----------------
-----------begin1------------
#include "a.h" 替換
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#ifndef header_aaa
#define header_aaa
-----------begin3------------
#include "b.h" 替換
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#ifndef header_bbb
#define header_bbb
class a;
class b
;#endif
-----------end3--------------
class a
;#endif
-----------end1-------------
-----------begin2------------
#include "b.h" 替換
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#ifndef header_bbb
#define header_bbb
class a;
class b
;#endif
-----------end2--------------
此時,無迴圈巢狀出現。編譯正常。
小結:相互使用時,注意不要相互#include "***"。
C 標頭檔案相互引用解決方案
簡化問題為 我們現在有a,b兩個類的標頭檔案,具體有a.h,a.cpp,b.h,b.cpp個資料夾。假如在a類中我們需要使用b類,在b類中需要使用a類,常規操作就是相互引用各自的標頭檔案。但是這樣會造成迴圈依賴的情況,就會報錯。1.前向宣告解決互相引用造成迴圈依賴 pragma once inclu...
標頭檔案相互引用優化問題
首先,兩個.m檔案互相引用.h檔案,不會出現問題的。但是比如在.h裡的某個屬性,型別是自定義的類,這時候如果只在.m裡引用就編不過了。這時候就要用 class。舉個例子 inte ce foo nsobject property nonatomic,strong bar somebar end就會報...
C 標頭檔案引用問題
c c 標頭檔案的引用問題 include使用 對於乙個工程 如下 在base中包含 func3.h,func3.c,資料夾main和資料夾func4 在main中包含 main.c,func1.h,func1.c和資料夾func2 在func2中包含 func2.h和func2.c 在func4中...