两个类#相互包含时出错
Error with two classes that #include each other
假设我有一个类叫Foo
,另一个类叫做Bar
。Bar
包含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;
};
相关文章:
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 猫鼬 - 包含标准C++库文件时出错
- 编译包含LLVM API标头的C++文件时出错
- 在Windows上设置CMake和vcpkg时出错"无法打开包含文件"
- 包含可可标头时出错
- 在 C++ 中包含库数据库.txt文件时出错
- ctime 包含 boost::文件系统时出错
- 当我包含 DirectXTex.h 时出错
- 编译包含 CPLEX 工具的项目时出错
- 在 Cygwin 64 上包含 boost.asio 时出错
- 使用 Qt 标头的递归包含时出错
- 将 Boost 标头包含在 .h 文件中但不包含在.cpp文件中时出错
- 当类包含boost::container::flat_set时,复制对象时出错
- 当我在 c++ 中不包含字符串头文件时出错
- 包含预编译头时出错
- 在c++项目中包含dlib库时出错
- 分配包含另一个结构数组的结构数组时出错
- 创建包含time_t的字符串时出错
- <QNetworkAccessManager><QNetworkReply> 在 BB10 应用程序开发的 cpp 文件中包含 时出错
- 两个类#相互包含时出错