Dependent Managent(環形依賴)

來源:互聯網
上載者:User

軟體開發有兩種依賴方式:

一種是編譯時間依賴,就是在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).

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.