C++中頭文件相互包含引發的問題:未定義

 

有兩個頭文件a.h和b.h

a.h中

#pragma once
#ifndef _A_H_
#define _A_H_

#include "b.h"

struct AInfo
{
    int a;
    int b;
};

#endif

b.h中

#pragma once
#ifndef _B_H_
#define _B_H_

#include "a.h"

class B
{
public:
    void fun1(AInfo aInfo, int n );
};

#endif

然後有兩個源文件a.cpp和b.cpp

a.cpp中

#include "a.h"
......

b.cpp中

#include "b.h"
......

編譯項目時會報錯,AInfo沒有定義。

a.cpp中包含頭文件a.h,在編譯之前,會在a.cpp中展開a.h而a.h又包含了b.h,所以也展開b.h,這時a.cpp就變成了類似下面的樣子:

class B
{
public:
    void fun1(AInfo aInfo, int n );
};

struct AInfo
{
    int a;
    int b;
};
......

此時,在結構體AInfo聲明之前,fun1中就用到了它,所以會產生AInfo沒有定義的錯誤信息所以應該將結構體的定義放在引用頭文件#include "b.h"之前就可以了。即將a.h改成如下:

#pragma once
#ifndef _A_H_
#define _A_H_

struct AInfo
{
    int a;
    int b;
};

#include "b.h"

#endif

同樣,展開b.cpp如下:

struct AInfo
{
    int a;
    int b;
};

class B
{
public:
    void fun1(AInfo aInfo, int n );
};
......

C/C++ 中頭文件習慣使用 #ifndef ... #define ... #endif 這樣的一組預處理標識符來防止重複包含,如果不使用的話,兩個頭文件相互包含,就出現遞歸包含。

參考:https://blog.csdn.net/hazir/article/details/38600419   C/C++ 中頭文件相互包含引發的問題

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章