base class undefined Error reason

來源:互聯網
上載者:User

自語:今天遇到的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吧。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.