[問題] include guard
開發平台(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
02/08 12:19, 1F
→
02/08 12:35, , 2F
02/08 12:35, 2F
→
02/08 12:36, , 3F
02/08 12:36, 3F
→
02/08 12:37, , 4F
02/08 12:37, 4F
→
02/08 12:37, , 5F
02/08 12:37, 5F
→
02/08 12:38, , 6F
02/08 12:38, 6F
→
02/08 12:38, , 7F
02/08 12:38, 7F
→
02/08 12:47, , 8F
02/08 12:47, 8F
推
02/08 14:17, , 9F
02/08 14:17, 9F
推
02/08 19:49, , 10F
02/08 19:49, 10F
推
02/11 19:40, , 11F
02/11 19:40, 11F
→
02/11 19:40, , 12F
02/11 19:40, 12F
→
02/11 20:13, , 13F
02/11 20:13, 13F
→
02/11 20:15, , 14F
02/11 20:15, 14F