问题
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