C++ 类,它的基类和循环包含包括

C++ class, its base class and circular include includes(C++ 类,它的基类和循环包含包括)

本文介绍了C++ 类,它的基类和循环包含包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件 #1 (foo.h):

FILE #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):

FILE #2 (bar.h):

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

文件 #3 (baseclass.h):

FILE #3 (baseclass.h):

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

但我在 class Foo : public baseclass:

Error: expected class-name before »{« token

如果我添加 class baseclass; 前类声明,我得到这个错误:

If I add class baseclass; bevor class declaration, I get this error:

Error: invalid use of incomplete type »struct baseclass«

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

So my question is, how can I resolve circular dependencies with baseclasses?

问你是否没有得到某个点.我已经尝试更改包含标题的顺序,但到目前为止还没有运气.感谢您的任何提示.

Ask if you don't get somepoint. I allready tried to change the order of includeing the headers, but no luck so far. Thanks for any hint.

注意:我正在使用包含警卫它不限于指针,所以我删除它们,以防万一.添加了基类(忘记了 O.o)现在应该很清楚并且没有任何缺陷,此代码仍然存在问题.

Note: I am using include guards It is not limited to pointers, so I remove them, just in case. Added baseclass (forgot O.o) Now it should be clear and without anymore flaws, the problem persisits with this code.

推荐答案

您似乎发布的是在 Foo 中有一个 Bar 成员,以及一个 <Bar 中的 code>Foo 成员.这是一个你需要打破的循环依赖——如果每个 Foo 都包含一个 Bar ,其中包含一个 Foo ,那么构造要么永远不会终止.

What you seem to have posted is to have a Bar member in the Foo, and a Foo member in the Bar. That is a circular dependency you need to break - if every Foo contains a Bar which contains a Foo then constructing either never terminates.

class Foo : public baseclass {
    public:
        Bar varBar;
};

class Bar {
    public:
        Foo varFoo;
};

相反,您需要在其中至少一个中使用对 FooBar 的指针或引用:

Instead you need to use a pointer or reference to the Foo or Bar in at least one of them:

class Bar;
class Foo : public baseclass {
    public:
        Bar& varBar;
};

class Bar {
    public:
        Foo varFoo;
};

由于循环被破坏并且您只使用对对象的引用,因此您不需要拥有被引用类型的完整定义,并且可以使用前向声明.

As the circularity is broken and you're only using a reference to the object, you don't need to have the full definition of the referred-to type, and can use a forward declaration.

包含守卫对用户有好处,但在开发时尽量不要依赖它们.如果编译器必须检查是否包含某些内容,即使它对守卫/编译指示进行了优化,它仍然可以工作.您确实需要了解什么取决于打破初始循环的因素,而对文件进行保护对您没有帮助.

Include guards are good for users, but try and not rely on them when developing. If the compiler has to check whether or not something has been included, it's still doing work even if it has optimisations for guards/pragmas. You do need to have some understanding of what depends on what to break the initial cycle, and putting guards on the files won't help you with that.

这篇关于C++ 类,它的基类和循环包含包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ 类,它的基类和循环包含包括