自語:今天遇到的bug,覺得很詭異,明明引用了標頭檔卻找不到基類定義,百度之後解決,覺得是個值得注意的地方,很細小,但是很難查~~~以後注意
不要把所有標頭檔都扔在一塊兒 之前寫程式時,最喜歡把類的標頭檔全部放到stdafx.h 或類似自訂的某個標頭檔中(如include_files.h),然後在不同的檔案中需要調用別的檔案中的類或變數或函數什麼的,只要直接#include "include_files.h"就行了,今天終於遇到了error C2504錯誤。具體說明如下:
有以下幾個檔案:include_files.h AA.h AA.cpp BB.h BB.cpp
view plaincopy to clipboardprint?
//include_files.h
#pragma once
...
#include "AA.h"
#include "BB.h"
...
// AA.h
#include "include_files.h"
class AA
{
public: ...
};
// BB.h
#include "include_files.h"
class BB : public AA
{
public: ...
}
//include_files.h
#pragma once
...
#include "AA.h"
#include "BB.h"
...
// AA.h
#include "include_files.h"
class AA
{
public: ...
};
// BB.h
#include "include_files.h"
class BB : public AA
{
public: ...
}
編譯後就會報錯C2504,未定義基類AA,msdn上的解釋是這樣的:
Missing include file. 未包含標頭檔
External base class not declared with extern. 外部類沒有用ertern定義。
而這個錯誤就是因為標頭檔包含得不明確。
編譯時間,首先編譯了AA.h,
因為AA.h中包含了include_files.h,所以又去編譯了include_files.h
include_files.h裡即包含AA.h又包含BB.h,所以繼續編譯
AA.h正在編譯中,於是再去編譯BB.h,而BB.h未編譯,但它裡面卻用到了類AA,然而此時我們仍在編譯AA.h的嵌套中,即AA.h未編譯完,顯然類AA還沒有明確定義,所以才報了錯。即如下一個過程。
view plaincopy to clipboardprint?
編譯AA.h...
編譯include_files.h
編譯AA.h, 根據#pragam once跳過
編譯BB.h
編譯include_files.h,根據#pragam once跳過
編譯class BB : public AA
報錯:error C2504:未定義基類AA...
編譯AA.h...
編譯include_files.h
編譯AA.h, 根據#pragam once跳過
編譯BB.h
編譯include_files.h,根據#pragam once跳過
編譯class BB : public AA
報錯:error C2504:未定義基類AA...
所以以後不能把類定義的標頭檔隨便扔在一塊了,還是勤快些,在用到時才#include吧。。。