我有 3 個 C 檔案:
主檔案
#include "FileA.h"
檔案A.h
#include "FileB.h"
class FileA{
private:
FileB* b; //It doesn't give error here!
};
檔案B.h
class FileB{
private:
FileA* A; //The error is here!
};
當我運行 Main.cpp 檔案時,編譯器說:
'FileA' does not name a type, did you mean 'FileB'?
這是我第一次使用 StackOverflow 提問,所以有點亂,抱歉。任何人都知道如何解決這個問題及其原因?先感謝您!
uj5u.com熱心網友回復:
#include前處理器指令復制檔案的內容。所以內容Main.cpp成為內容FileA.h,因為這#include是檔案中唯一的運算式。
該檔案FileA.h首先包含FileB.h以下內容Main.cpp:
Main.cpp前處理器輸出:
class FileB{
private:
FileA* A; //The error is here!
};
class FileA{
private:
FileB* b; //It doesn't give error here!
};
FileA正如您在尚未宣告錯誤的行上看到的那樣。由于兩者都FileA需要FileB彼此,因此您需要在每個標題中使用之前對類進行 delcare。并且不要忘記防止遞回包含。我使用#pragama oncebecause 更簡單,并且在所有主要編譯器上都受支持,即使它不是標準的:
主檔案
#include "FileA.h"
檔案A.h
#pragma once
#include "FileB.h"
class FileB;
class FileA{
private:
FileB* b;
};
檔案B.h
#pragma once
#include "FileA.h"
class FileA;
class FileB{
private:
FileA* A;
};
uj5u.com熱心網友回復:
花了太多時間評論而不是回答。這幾乎就是 Bolov 所展示的,但有更多血腥的細節。
讓我們看看編譯器的做法。每當編譯器(實際上是前處理器)找到一個include指令時,它就會將 替換include為包含檔案的內容。
編譯器從 Main.cpp 開始。它看到
#include "FileA.h"
并用 FileA.h 替換它,所以現在你有了
#include "FileB.h"
class FileA{
private:
FileB* b; //It doesn't give error here!
};
編譯器從中斷的地方繼續并找到
#include "FileB.h"
并將其替換為 FileB.h。現在你有
class FileB{
private:
FileA* A; //The error is here!
};
class FileA{
private:
FileB* b; //It doesn't give error here!
};
不需要更多的前處理器作業,因此編譯器會查看組合檔案。FileB是第一個定義的東西,它需要一個FileA滿足的宣告FileA* A;。編譯器FileA還沒有看到,所以它會發出一個錯誤并繼續運行。它找到FileA了FileB* b;成員,但此時它已經看到了FileB,所以沒有錯誤。
當你有一個指標或參考時,編譯器知道識別符號存在就足夠了,即使它不知道命名型別是什么樣的,因為它不必保存該型別的實體。解決方法是轉發宣告FileA ahead of FileB`
class FileA; // forward declaration
class FileB{
private:
FileA* A; //The error is here!
};
class FileA{
private:
FileB* b; //It doesn't give error here!
};
現在FileA* A;很滿意有這樣的東西 aFileA它還沒有足夠的知識來構造一個或如何訪問 a 中的任何東西FileA,但是沒有人要求它這樣做。
這決議為一個看起來像的 FileB.h
class FileA; // forward declaration
class FileB{
private:
FileA* A; //The error is here!
};
Bolov 提出了一個很好的觀點,即防止同一檔案的多個包含。有時您可以僥幸逃脫,但通常您會遇到遞回回圈和幾乎難以理解的錯誤訊息。最好避免選擇Include Guard機制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519683.html
標籤:C 班级指针
上一篇:為什么我能夠更改C中的字串常量?
