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

标签 c++ friend circular-dependency

为什么下面的代码不能编译,我该如何修复它?我得到的错误是:

Use of undeclared identifier 'Foo'

尽管 Foo 在错误发生的地方(在 Barfriend 声明处)明确声明和定义。

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/

相关文章:

c++ - 在模板类中构造对象需要异常初始化

c++ - XPATH在C++ Boost中使用

c++ - 为什么匿名 unique_ptr 值会立即被破坏

c++ - 理解以下 C++ 代码时遇到问题。 (寻求)

c++ - 关于友元函数定义和命名空间范围

c++ - 成为模板模板参数的 friend

Python、循环依赖和单例

c++ - 与 extern "C"函数的友元似乎需要::来限定名称

javascript - 有没有办法从 Angular 依赖注入(inject)中摆脱循环依赖

c++ - C++ 中的循环依赖