两个类#相互包含时出错

Error with two classes that #include each other

本文关键字:包含时 出错 两个      更新时间:2023-10-16

假设我有一个类叫Foo,另一个类叫做BarBar包含Foo的一个实例,而我在Foo中有一个函数,它将Bar作为参数。然而,当我在Foo#include "Bar.h"以允许Foo看到Bar时,我在引用Bar的行上得到了这个错误:

错误:ISO C++禁止声明没有类型的"Foo"

我猜这是因为这两个类都依赖于彼此进行编译。有什么办法绕过这个吗?

EDIT:这两个类都有头文件,其中另一个类在#ifndef声明中被引用。

Foo.h中,您需要使用前向声明class Bar;,而不是包括Bar.h。请注意,要使其工作,您需要将参数Bar作为Foo类中的引用或指针。

class Foo;
class Bar
{
};
and
class Bar;
class Foo
{
};

但这可能是错误设计的结果

您需要为至少一个类使用前向声明:

Foo.h:

#include "Bar.h"
class Foo {
};

Bar.h:

class Bar;
#include "Foo.h"
class Bar {
};

还要注意,你不能轻易地在Foo.h中引用Bar的成员(他们没有声明)。因此,任何需要Bar的内联成员都必须进入Foo.cpp(或者.cc,如果你愿意的话)。您也不能将Bar作为Foo的值成员。

因此:

class Bar {
    Foo f; // OK. Compiler knows layout of Foo.
};
class Foo {
    Bar b; // Nope. Compiler error, details of Bar's memory layout not known.
    Bar *b; // Still OK.
};

这对于模板来说尤其棘手。如果您遇到问题,请参阅常见问题解答。

对参数和前向声明使用引用或指针。例如

//foo.h
class Bar;// the forward declaration
class Foo {
void myMethod(Bar*);
};
//foo.cpp
#include "bar.h"
void Foo::myMethod(Bar* bar){/* ... */}
//bar.h 
#include "foo.h"
class Bar {
  /*...*/
  Foo foo;
};