c++ - 被通告扼杀的 friend 功能包括

标签 c++ include friend circular-dependency

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 ,以及类 FG (等)#include class B自用shared_ptr<B> .
而且,因为类 FG现在也坏了:

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 class B for shared_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/

相关文章:

file - 在主文件中包含一个辅助文件

javascript - 在js文件中包含jquery

c++ - C++ 中的 friend 成员函数 - 前向声明不起作用

.net - friend 引用课?

C++ : friends of class and "this" pointer

c++ - 当 -std=c++17 在编译器输出中时,编译器请求通过使用 -std++17 标志为 std::variant 启用 c++17 支持

c++ - 在 Qt 中以 root 身份执行 Linux 命令

C++ 先前定义错误

c++ - 自定义 vector 类中的堆损坏错误

c++ - QuantLib C++ 库 - FixedRateBond 优惠券