类 A
是类 B
的实例的唯一实例化器和容器.
所以创建类 B
的构造函数似乎是个好主意private,并且只能通过类 B
中声明的友元函数调用它并在类 A
中定义.
文件 A.h(编辑:包含在 B 类中定义的枚举)
#ifndef A_H
#define A_H
#include "B.h"
using namespace std;
class A
{ public:
A();
shared_ptr<B> CreateBInstance( const B::ENUM_STANDARD_COLORS );
shared_ptr<B> CreateBInstance( const string ); // Custom color
private:
unique_ptr<map<int, shared_ptr<B>>> UPTR__BInstancesMap;
}
#endif
文件 B.h(编辑:包含 B 类中定义的枚举)
#ifndef B_H
#define B_H
#include "A.h" // Causes chaos
using namespace std;
class B
{ public:
enum class ENUM_STANDARD_COLORS : unsigned int
{ ... // ~70 standard colors
};
private:
B();
friend
shared_ptr<B> A::CreateBInstance( const ENUM_STANDARD_COLORS );
friend
shared_ptr<B> A::CreateBInstance( const string ); // Custom color
}
#endif
类 A
需要类 B
的完整声明 (#include)对于 shared_ptr<B>
.
类 B
需要一些类声明 A
对于 friend 功能。
一个简单的前向声明会导致错误:
invalid use of incomplete type 'struc A'
在友元函数声明处。
完整声明 (#include) 更糟糕:
error: prototype for 'std::shared_ptr A::CreateInstance()' does not match any in class 'A'
(但确实如此!)在友元函数声明处。
而且,因为类 B
现在坏了:
error: 'B' was not declared in this scope
error: template argument 1 is invalid
每次提到 B
时都会出现在类里面A
,以及类 F
和 G
(等)#include class B
自用shared_ptr<B>
.
而且,因为类 F
和 G
现在也坏了:
error: 'F' was not declared in this scope
error: template argument 1 is invalid>
error: 'G' was not declared in this scope
error: template argument 1 is invalid
每次提到 F
时都会出现和 G
在类里面A
.
不幸的是,包含守卫并不能阻止循环包含。
有没有办法让这个好友功能起作用?我从来没有一次犯过这么多错误!
最佳答案
Class
A
requires a full declaration (#include) of classB
forshared_ptr<B>
.
不,前向声明在A.h
中就足够了. shared_ptr
(和 unique_ptr
)不需要类 B
返回类型声明[1] 和类数据成员声明的完整类型。
文件A.h
#ifndef A_H
#define A_H
class B; // forward declaration
using namespace std;
class A
{ public:
A();
shared_ptr<B> CreateBInstance();
private:
unique_ptr<map<int, shared_ptr<B>>> UPTR__BInstancesMap;
};
#endif
[1] “常规”类型也是如此 T
这不是 shared_ptr
.
关于c++ - 被通告扼杀的 friend 功能包括,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38888976/