說我有以下兩類:循環依賴
// a.h
#include "b.h"
和:
// b.h
include "a.h"
我知道有過一個問題在這裏,但我怎麼能解決這個問題,並使用a
對象和他們的方法在b
類中,反之亦然?
說我有以下兩類:循環依賴
// a.h
#include "b.h"
和:
// b.h
include "a.h"
我知道有過一個問題在這裏,但我怎麼能解決這個問題,並使用a
對象和他們的方法在b
類中,反之亦然?
您可以使用所謂的「前向聲明」。
對於函數,這會是這樣void myFunction(int);
。對於一個變量,它可能看起來像extern int myVariable;
。對於一個班級,class MyClass;
。這些無形語句可以包含在實際的代碼聲明之前,併爲編譯器提供足夠的信息來生成使用聲明類型的代碼。
爲了避免出現問題具有圓形包括,使用「包括防護件」 - 一個#ifdef
在這防止它的每個頭文件的頂部被包括兩次。
這個答案沒有討論這個東西的真正核心,那就是你限制你在'A'的標題中提到'B'來轉發可聲明的東西,但是在'A'的源文件中你可以自由地'#include'完整的定義,因爲沒有任何東西會包含'#include'源文件......你將不會有任何循環依賴關係。這個_only_會影響標題,這就是我們如何利用有效削弱類型使用的方法。 –
「其他」類只能具有引用或指向「第一個」類的指針。
文件啊:
#include "b.h"
struct a {
b m_b;
};
文件BH:
struct a;
struct b {
a* m_a;
};
void using_the_a_instance(b& theb);
文件b.cpp:
#include "b.h"
#include "a.h"
void using_the_a_instance(b& theb)
{
theb.m_a = new a();
}
要延長@Borealid的回答是:
爲了避免通告中包含的問題,使用「包含警衛」
例如,
#ifndef MYFILE_H /* If this is not defined yet, it must be the first time
we include this file */
#define MYFILE_H // Mark this file as already included
// This only works if the symbol we are defining is unique.
// code goes here
#endif
StackOverflow上的幽靈說, 「* Uhhhhhhnnnn ... Neeeeed moooore cooooode ...... *」 –
我沒有看到有什麼課,所以我downvoting。 –