多个包含在多个文件中

我正在做一个小游戏。 在BattleRecord.h中:
#ifndef _CHARACTER_H_
#define _CHARACTER_H_
#include "Character.h"
#endif

class BattleRecord
{
public:
    Character Attacker;
    Character Defender;
    Status status;
    int DamageDealt;    
    int GoldEarned;
    int ExpGained;
};
在Character.h中:
#ifndef _EQUIPMENT_H_
#define _EQUIPMENT_H_
#include "Equipment.h"
#endif

class BattleRecord;
class Character
{
BattleRecord AttackEnemy(Character &Enemy);
}
在BattleRecord.h中:
#ifndef _CHARACTER_H_
#define _CHARACTEr_H_
#include "Character.h"
#endif

#ifndef _BATLE_RECORD_H_
#define _BATLE_RECORD_H_
#include "BattleRecord.h"
#endif

class GUI
{
public:
//GUI Methods, and two of these:
void ViewStats(Character &Player);
void Report(BattleRecord Record)
}
这里的问题是,我的Character.h和BattleRecord.h需要相互包含,这肯定会导致多重重新定义问题。因此,我在Character.h中使用了前向声明,添加:
class BattleRecord;
这个问题已经解决了。但是,GUI.h再次需要BattleRecord.h来报告战斗,因此我必须将BattleRecord.h包含在GUI.h中。我还必须包含Character.h才能传入ViewStat函数。我得到了错误并坚持到这个piont。     
已邀请:
你使用包含警卫错了。它们应出现在您打算仅防止多个包含的文件中,并且它们应覆盖整个文件。 (不只是包括)。 例如,在BattleRecord.h中
#ifndef _BATTLE_H_
#define _BATTLE_H_
#include "Character.h"

class BattleRecord
{
public:
    Character Attacker;
    Character Defender;
    Status status;
    int DamageDealt;    
    int GoldEarned;
     int ExpGained;
};

#endif // _BATTLE_H_
    
如果你的编译器支持这个,那么把你的
#endif
放在文件的末尾而不是你的包含的末尾,或者在顶部使用
#pragma once
,尽管它不那么便携。 编辑: 进一步解释
#ifdef
&
ifndef
的作用是告诉编译器完全包含或排除编译。
// if _UNQIUEHEADERNAME_H_ is NOT defined include and compile this code up to #endif
#ifndef _UNQIUEHEADERNAME_H_
// preprocessor define so next time we include this file it is defined and we skip it
#define _UNQIUEHEADERNAME_H_
// put all the code classes and what not that should only be included once here
#endif // close the statement 
您想要这样做的原因是因为包含头文件基本上是说“将所有代码放在此文件中”,如果您多次执行此操作,那么您将在重新定义对象时出现命名冲突并在最佳方案中减慢编译时间。     
一般来说,使用前向声明而不是包含。这可以最大限度地减少包含文件所包含的数量。唯一的例外是当您定义的类是派生类时,则需要包含基类。     
除了上面提到的包含保护问题(你还有_CHARACTEr_H _ / _ CHARACTER_H_不匹配可能会导致你在GUI.h的第2行出现问题),你可能想要修改你的对象设计,以便角色不会攻击强制(),但是有一个Battle()类,其中引用了两个角色,并且在战斗之后产生了BattleRecord。这将阻止角色类首先不必了解BattleRecords,允许未来进行多角色战斗的可能性,进行多回合战斗,或通过继承战斗类进行特殊战斗。     
好的,大家好 谢谢你的帮助。我按照建议重写了头文件的所有内容,现在它完美无瑕。花了很多时间,因为我为很多课程做错了。     

要回复问题请先登录注册