为什么下面的代码不能编译,我该如何修复它?我得到的错误是:
Use of undeclared identifier 'Foo'
尽管 Foo
在错误发生的地方(在 Bar
的 friend
声明处)明确声明和定义。
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是上述代码的可编译在线版本。
最佳答案
将 FooChild
放在它自己的头文件中。
foo.h:
#ifndef FOO_H
#define FOO_H
class Bar;
class Foo {
public:
void Func(const Bar&) const;
};
#endif
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++ - 如何解决 C++ 中友元声明的循环依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535434/