假设我有一个名为Foo
的类和另一个名为Bar
的类。Bar
包含Foo
的一个实例,我在Foo
中有一个函数,它将Bar
作为参数。但是,当我在#include "Bar.h"
in Foo
中允许Foo
看到Bar
时,在引用Bar
的行上会出现此错误:
错误: ISO C++禁止没有类型的“Foo”声明
我猜这是因为这两个类相互依赖来编译。有什么办法可以绕过这件事吗?
编辑:这两个类都有头文件,其中在#ifndef
声明中引用了另一个类。
发布于 2012-03-11 22:25:39
在Foo.h
中,您需要使用前向声明class Bar;
,而不是包含Bar.h
。请注意,要使其工作,需要将参数Bar
作为Foo
类中的引用或指针。
发布于 2012-03-11 22:26:52
对参数和前向声明使用引用或指针。例如。
//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;
};
发布于 2012-03-11 22:34:37
您至少需要对一个类使用前向声明:
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.
};
对于模板来说,这特别棘手。如果你有麻烦,请看常见问题。
https://stackoverflow.com/questions/9662557
复制