兩個類相互依賴:
class Object { public: NewType ToType(); };
class NewType : public Object { };
分別放在 Object.h、NewType.h 中,若雙向 #include 會導致遞迴包含,編譯器報錯:C4182(嵌套層級過深)、C1076(堆疊耗盡)。
| 嘗試 | 做法 | 結果 |
|---|---|---|
| 1 | 雙向 include 無防禦 | 遞迴包含,堆疊溢位 |
| 2 | 雙向 include + 雙重 include guard | 守衛生效前已遞迴,同樣失敗 |
| 3 | Object.h 先 guard 再 include NewType.h | C2504: 'Object' : base class undefined |
| 4 | NewType.h 先 guard 再 include Object.h | C2146: missing ';' before 'ToType'、C2501: missing storage-class |
#include 展開是文本替換,守衛只能防止同一文件重複展開,無法阻斷 A→B→A 的交叉遞迴;#ifndef _OBJECT_H
#define _OBJECT_H
class NewType; // 前向宣告:僅告知編譯器「有這個類」
class Object {
public:
NewType ToType(); // 返回值用不完整類型合法(非 by value)
};
#endif
#ifndef _NEWTYPE_H
#define _NEWTYPE_H
#include "Object.h" // 此時 Object 定義已完整
class NewType : public Object {
// 派生類定義
};
#endif
#include "Object.h"
#include "NewType.h" // 實現需完整定義
NewType Object::ToType() {
return NewType(); // 或具體構造邏輯
}
A.h → B.h 只在 A.cpp 中實現;IObject,雙方依賴介面而非實現;