C++ 类,其基类和循环包含 [重复]

2024-04-12

文件 #1 (foo.h):

#ifndef FOO_H_
#define FOO_H_
#include "baseclass.h"
#include "bar.h"
class Bar;
class Foo : public baseclass {
public:
bar *varBar;
};
#endif

文件 #2 (bar.h):

#ifndef BAR_H_
#define BAR_H_
#include "foo.h"
class Foo;
class Bar {
public:
Foo *varFoo;
};
#endif

文件#3(baseclass.h):

#ifndef BASECLASS_H_
#define BASECLASS_H_
#include "foo.h"
class Foo;
class baseclass {
public:
list<Foo*> L;
};
#endif

但我在文件 #1 中收到编译错误class Foo : public baseclass:

Error: expected class-name before »{« token

如果我添加class baseclass;在类声明之前,我收到此错误:

Error: invalid use of incomplete type »struct baseclass«

所以我的问题是,如何解决基类的循环依赖关系?

如果你没有得到一些要点,请询问。我已经尝试更改包含标题的顺序,但到目前为止还没有运气。 感谢您的任何提示。

编辑:注意:我正在使用包含防护 EDIT2:它不限于指针,所以我删除它们,以防万一。 EDIT3:添加基类(忘记O.o) EDIT4:现在应该很清楚并且没有更多缺陷,问题仍然存在于这段代码中。


通常的方法是在头文件中添加以下内容:

#ifndef FOO_H_
#define FOO_H_
#include "baseclass.h"
#include "bar.h"
class Bar;
class Foo : public baseclass {
public:
bar *varBar;
};
#endif

and

#ifndef BAR_H_
#define BAR_H_
#include "foo.h"
class Foo;
class Bar {
public:
Foo *varFoo;
};
#endif

大多数编译器(gcc、VC)也接受#pragma once在文件的开头,但我很确定它不是当前 C++ 标准的一部分。


EDIT:

果然,正如 ISO/IEC 14882 所规定的,#pragma "causes the implementation to behave in an implementation-defined manner. Any pragma that is not recognized by the implementation is ignored."

目前与C++0x还是一样。

所以我会坚持使用第一种老式的方法;-)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ 类,其基类和循环包含 [重复] 的相关文章

随机推荐