如何解决c++中友元声明的循环依赖
How to resolve circular dependency with friend declarations in C++?
为什么下面的代码不能编译,我该如何修复它?我得到的错误是:
使用未声明的标识符'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
相关文章:
- 如何在嵌套类中正确使用友元声明?
- 将子类方法声明为基类的友元
- 在将函数声明为友元时,尖括号的含义是什么?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- C++ 17 个友元函数声明和内联命名空间
- 将派生类的构造函数声明为父类的友元
- 为什么 gcc 无法从其前向声明中检测到友元类命名空间?
- 类模板中文本运算符的友元声明
- 以嵌套类为参数的友元模板声明
- 模板和隐式构造函数的类定义之外的友元声明
- 如何将友元声明用于具有约束的模板类
- 为什么我不能定义一元运算符,然后在 MSVC 的模板类中声明具有相同名称的友元二进制运算符?
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 如何将模板友元函数声明为可变参数类
- 嵌套友元类所需的前向声明
- 在派生类或基类中,我应该在哪里声明友元类
- 类定义交叉引用时如何声明友元方法
- 在此范围内未声明友元函数错误
- GCC声明友元函数是重载的,有歧义调用,clang编译
- 声明友元函数时出现变量作用域错误