軟體開發有兩種依賴方式:
一種是編譯時間依賴,就是在b.h檔案中添加#include“a.h”
第二種是連結時依賴,是指產生的目標檔案a.o在尋找可用符號時要去別的目標檔案中去尋找。例如,在a.h中存在extern int n;那麼在產生的a.o檔案裡就需要去別的目標檔案中尋找n的定義,這就構成了連結時依賴。
假定存在兩個類CLASS A CLASS B.(在UML中,依賴關係用--------->表示)
如果在這兩個類之間發生依賴關係的話,存在以下幾種方式:
1)class A中含有B類性或者B指標類型的變數。
2)classA派生自classB
3)classA中某個函數需要classB型別參數。
4)classA中某個函數需要classB類型的static 參數。
5)classA需要給classB傳遞訊息。
在以上幾種情況,都需要在classA的cpp檔案中,添加#include<classB.h>.
代碼重用,作為重要的設計目標,必然產生依賴。在你添加#include<classB.h>的同時,也將classB.h中的標頭檔也相應的添加了進來,這樣大大增加了compile time,而且最大的問題是,容易發生circular dependency,導致編譯不通過,報錯:“找不到基類”。
PS:環形依賴是請參考http://en.wikipedia.org/wiki/Circular_dependency。
解決方案:在某一個環節中, 採用forward declaration(前向聲明)的方式,來打斷由於#include<>所帶來的環。
原文:
A
forward declaration of a class declares its name as a valid class name but leaves out its definition. This permits that name to be used as a type for pointers and references that are not dereferenced before the definition
is encountered. Forward declarations make it possible for classes to have circular relationships without having circular dependencies between header files (which the compiler will not permit).