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

How to resolve circular dependency with friend declarations in C++?

本文关键字:声明 友元 循环 依赖 c++ 何解决 解决      更新时间:2023-10-16

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

使用未声明的标识符'Foo'

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

foo。:

#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

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

FooChild放到自己的头文件中

foo:

#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