如何解决 C++ 中友元声明的循环依赖?

eml*_*lai 5 c++ circular-dependency friend

为什么以下代码无法编译以及如何修复它?我得到的错误是:

使用未声明的标识符“Foo”

尽管Foo在错误发生的地方(在friend中的声明处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
Run Code Online (Sandbox Code Playgroud)

foo.cpp

#include "foo.h"

void Foo::Func(const Bar& B) const {
  // do stuff with B.X
}
Run Code Online (Sandbox Code Playgroud)

酒吧.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
Run Code Online (Sandbox Code Playgroud)

是上述代码的可编译在线版本。

R S*_*ahu 3

放入FooChild自己的头文件。

foo.h:

#ifndef FOO_H
#define FOO_H

class Bar;

class Foo {
public:
  void Func(const Bar&) const;
};

#endif
Run Code Online (Sandbox Code Playgroud)

foochild.h:

#ifndef FOOCHILD_H
#define FOOCHILD_H

#include "foo.h"
#include "bar.h"

class FooChild : public Foo {
  friend void Bar::Func(FooChild*);
};

#endif
Run Code Online (Sandbox Code Playgroud)