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

随声附和 提交于 2021-02-10 05:39:32

问题


Why doesn't the following code compile and how can I fix it? The error I get is:

Use of undeclared identifier '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.


回答1:


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:

#ifndef FOOCHILD_H
#define FOOCHILD_H

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

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

#endif


来源:https://stackoverflow.com/questions/30535434/how-to-resolve-circular-dependency-with-friend-declarations-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!