如何用C ++中的友人声明解决循环依赖关系? [英] How to resolve circular dependency with friend declarations in C++?
本文介绍了如何用C ++中的友人声明解决循环依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么以下代码无法编译,我该如何解决?我得到的错误是:
Why doesn't the following code compile and how can I fix it? The error I get is:
使用未声明的标识符"Foo"
Use of undeclared identifier 'Foo'
尽管在错误发生的位置(在 Bar
中的 friend
声明中)明确声明并定义了 Foo
.
although Foo
is clearly declared and defined at the point where the error occurs (at the friend
declaration in Bar
).
foo.h :
#ifndef FOO_H
#define FOO_H
#include "bar.h" // needed for friend declaration in FooChild
class Foo {
public:
void Func(const Bar&) const;
};
class FooChild : public Foo {
friend void Bar::Func(FooChild*);
};
#endif
foo.cpp :
#include "foo.h"
void Foo::Func(const Bar& B) const {
// do stuff with B.X
}
bar.h :
#ifndef BAR_H
#define BAR_H
#include "foo.h"
class Bar {
public:
void Func(FooChild*) {}
private:
int X;
friend void Foo::Func(const Bar&) const; // "use of undeclared identifier 'Foo'"
};
#endif
此处是上述代码的可编译在线版本.
Here's a compilable online version of the above code.
推荐答案
将 FooChild
放入其自己的头文件中.
Put FooChild
in a header file of its own.
foo.h:
#ifndef FOO_H
#define FOO_H
class Bar;
class Foo {
public:
void Func(const Bar&) const;
};
#endif
foochild.h:
foochild.h:
#ifndef FOOCHILD_H
#define FOOCHILD_H
#include "foo.h"
#include "bar.h"
class FooChild : public Foo {
friend void Bar::Func(FooChild*);
};
#endif
这篇关于如何用C ++中的友人声明解决循环依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文