C++的两个头文件相互包含

C++ two header files include each other

本文关键字:文件 包含 两个 C++      更新时间:2023-10-16

有三个.h文件

A.h:

#ifndef __A_H__
#define __A_H__
#include"Card.h"
#include"B.h"
struct A{
    Card card;
    .....
};
void getCards(A *a, int num);
#endif

B.h

#ifndef __B_H__
#define __B_H__
#include"Card.h"
#include"A.h"
struct B{
    Card card;
    .....
};
void getCards(A *a, B *b, int num);
#endif

卡片.h

#ifndef __CARD_H__
#define __CARD_H__
struct Card{
    int num;
    char *type;
};
#endif

由于A.hB.h彼此包括,所以并非所有头文件都包括在内。

请给我一些建议。

据我所见,您不需要在"A.h"文件中包含"B.h"。因此,删除它以减少依赖关系。在"B.h"文件中包含"A.h"似乎也没有必要。简单的远期申报就足够了。

B.h

#ifndef __B_H__
#define __B_H__
#include"Card.h"
class A; // then you will have to include A.h in your B.cpp file
struct B{
    Card card;
    .....
};
void getCards(A *a, B *b, int num);
#endif