[問題] include guard

看板C_and_CPP作者 (傷神客)時間13年前 (2013/02/08 12:15), 編輯推噓4(4010)
留言14則, 6人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) GCC 問題(Question): 假設目前有兩個header file, 分別宣告了class A以及B 並且因為class A B有相依性, 所以相互include 但如下述程式碼 會導致 Class B中的A找不到 因為A先把自己guard住後去 include B.hpp 當B認為她要include A 因為A已經GUARD了 導致沒辦法 include 所以在B中就找不到A的宣告 請問這樣有甚麼漂亮的解法嗎? 這個情況下 只有在A中用 extern class B; 而不去include才是解法嗎? (請不要叫我把a.hpp b.hpp合起來或progma once -----header file a.hpp #ifndef A_H #define A_H #include "b.hpp" class A{ B computation(); } #endif -----header file b.hpp #ifndef B_H #define B_H #include "a.hpp" class B{ A computation(); } #endif ----- main.cpp #include "a.hpp" int main(){ A a; } 用extern class B 的缺點是當以下情況發生時 因為inline必須直接看到定義了甚麼, 所以不能只是extern ----header file a.hpp #ifndef A_H #define A_H #include "b.hpp" class A{ B comp(){B b; return b.comp();} A comp2(){A a; return a;} } #endif ----header file b.hpp #ifdef B_H #define B_H #include "a.hpp" class B{ inline A comp(){A a; return a.comp2();} } ---- main.cpp #include "A.hpp" int main(){ A a; } 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.126.187.85 ※ 編輯: privatewind 來自: 59.126.187.85 (02/08 12:15)

02/08 12:19, , 1F
A,B 明明共生,又堅持要分成兩個 hpp 到底意義何在
02/08 12:19, 1F

02/08 12:35, , 2F
如果以學習的角度來看 我想知道有沒有解法
02/08 12:35, 2F

02/08 12:36, , 3F
實務上則是 A B雖然共生 但是他的聯繫相當低
02/08 12:36, 3F

02/08 12:37, , 4F
可能是100多個function 才有這樣一個共生的問題存在
02/08 12:37, 4F

02/08 12:37, , 5F
我目前也確實遇到了這樣的一個問題
02/08 12:37, 5F

02/08 12:38, , 6F
以抽象化的角度來看的話 因為A B的關係太低 放在
02/08 12:38, 6F

02/08 12:38, , 7F
同一個header file中反而顯得突兀
02/08 12:38, 7F

02/08 12:47, , 8F
1. Forward Declaration. 2. Design with Interface.
02/08 12:47, 8F

02/08 14:17, , 9F
會交互相依表示切割得不好 把那部份移出來獨立成C吧
02/08 14:17, 9F

02/08 19:49, , 10F
Forward Declaration +1
02/08 19:49, 10F

02/11 19:40, , 11F
forward declaration 使用的先決條件是不需要知道 size
02/11 19:40, 11F

02/11 19:40, , 12F
不過照原波給的例子真的很像循環相依
02/11 19:40, 12F

02/11 20:13, , 13F
Forward Declaration 還是需要知道 Size,只是 Pointer
02/11 20:13, 13F

02/11 20:15, , 14F
和 Reference 的 Size,Compiler 還滿了解的
02/11 20:15, 14F
文章代碼(AID): #1H57lEuA (C_and_CPP)