C++ 类的双向包含&;模板实例

C++ 类的双向包含&;模板实例,c++,class,inheritance,templates,typedef,C++,Class,Inheritance,Templates,Typedef,在试图将这两个类(Army和General)编译到它们自己的头文件中时,我遇到了一个问题: #ifndef ARMY_H #define ARMY_H #include "definitions.h" #include "UnitBase.h" #include "UnitList.h" #include "General.h" class Army { public: Army(UnitList& list); ~Army(void); Un

在试图将这两个类(Army和General)编译到它们自己的头文件中时,我遇到了一个问题:

#ifndef ARMY_H
#define ARMY_H

#include "definitions.h"
#include "UnitBase.h"
#include "UnitList.h"
#include "General.h"

class Army
{
public:
    Army(UnitList& list);       
    ~Army(void);

    UnitBase& operator[](const ushort offset);
    const UnitBase& operator[](const ushort offset) const;

    const uint getNumFightUnits() const;
    const ushort getNumUnits() const;

    const General<Warrior>* getWarrior() const;

private:
    UnitBase** itsUnits;
    uint itsNumFightUnits;
    ushort itsNumUnits;
    WarriorGeneral* itsGeneral;     
};

#endif
它们甚至不是未解决的链接器问题。。。注意,我将WarriorGeneral的typedef放在General.h文件中。我不知道这是否正确。有什么办法可以让这一切顺利进行吗

提前谢谢

您可以使用

template <class T> class General;
模板类通用;
使用该代码(剪切并粘贴到同一个cpp文件中,#include位于通用位处),如果定义了这三个而不是#include“generalbase”,则使用g++时不会出现错误:

没有通用数据库:

src/Army.cpp:13: error: expected class-name before ‘,’ token
没有勇士:

src/Army.cpp:26: error: ‘Warrior’ was not declared in this scope
src/Army.cpp:26: error: template argument 1 is invalid
src/Army.cpp:26: error: invalid type in declaration before ‘;’ token
没有单位列表

src/Army.cpp:32: error: expected ‘)’ before ‘&’ token

所以很难看出你的错误是什么;也许你错误地定义了GENERAL_H,而没有包括它?

我不知道陆军.H第21行是什么,因为你发布的那行没有那么多。我能看到的唯一未在该标题中声明的内容是
UnitList
。它是否正确地进行了转发声明,或者有一个您没有显示的标题包含


generalbase.h
Warrior.h
是否包括
Army.h
?如果是这样的话,这将导致表面上的循环包含。试着让它不做包含,而是向前声明
陆军

是的,@Mark B.做对了!我从GeneralBase.h中删除了Army.h,现在它可以完美地编译。然而,这让我想知道,如果我需要在通用数据库中包含Army.h,会发生什么…

我想告诉你的一件事是,析构函数甚至不能将
void
作为它们的参数。所以<代码>~军队(无效)
~常规(无效)是非法的。编辑:请发布完整的代码。@Prasoon Saurav:这不正确
f(void)
相当于
f()
。析构函数的规则也不例外,所以
~T(void)
是有效的。@James:谢谢你纠正我,我有点搞砸了。:-)已更新代码以包含整个.h文件,抱歉!。包括单元列表。将军基地。h包括军队。h。。。让我看看,谢谢@克里斯蒂安:不如告诉我们第21行到底是什么,而不是让我们算数好吗?你不必武断地把陆军也包括进去;你会有一个明确的理由。不知道原因是什么,我们帮不了你。我们所能说的是,你应该能够想出如何在没有包含的情况下获得你想要的东西。
src/Army.cpp:13: error: expected class-name before ‘,’ token
src/Army.cpp:26: error: ‘Warrior’ was not declared in this scope
src/Army.cpp:26: error: template argument 1 is invalid
src/Army.cpp:26: error: invalid type in declaration before ‘;’ token
src/Army.cpp:32: error: expected ‘)’ before ‘&’ token