无法访问 Friend 的私有构造函数 class

Cannot access private constructors of a Friend class

我有以下两个class:

struct Entity 
{
    unsigned id;
    Entity(unsigned id);
    Entity();
};

class EntityManager
{
public:
    Entity create();
    ...

private:
    Entity make_entity(unsigned index, unsigned generation);
};

目前效果很好。问题是封装。我不想允许直接创建 class Entity.

因此,我的目标是使 Entity 的构造函数成为私有的。然后我可以(据我所知)通过使 Entity 成为 EntityManagerfriend 来维护 EntityManager 中的功能。

因此进行更改将是结果:

struct Entity 
{
    unsigned id;
private:
    Entity(unsigned id);
    Entity();
};

class EntityManager
{
    friend struct Entity;
public:
    Entity create();

private:
    Entity make_entity(unsigned index, unsigned generation);
};

这破坏了代码。我得到的错误是这个:

entity_manager.cpp: In member function ‘Entity EntityManager::make_entity(unsigned int, unsigned int)’:
entity_manager.cpp:12:1: error: ‘Entity::Entity(unsigned int)’ is private
 Entity::Entity(unsigned id) : id(id) {}
 ^
entity_manager.cpp:19:21: error: within this context
     return Entity(id);
                     ^

实现文件是这样的:

Entity::Entity() : id(0) {}
Entity::Entity(unsigned id) : id(id) {}

Entity EntityManager::make_entity(unsigned idx, unsigned  generation)
{
    unsigned id = 0;
    id = ...
    return Entity(id);
}

Entity EntityManager::create()
{
    ...
    return make_entity(..., ...);
}

这里有什么我明显遗漏的吗?我还尝试在实现中调用 Entity(id) 作为 Entity::Entity(id),但我又收到另一个错误:

entity_manager.cpp: In member function ‘Entity EntityManager::make_entity(unsigned int, unsigned int)’:
entity_manager.cpp:19:29: error: cannot call constructor ‘Entity::Entity’ directly [-fpermissive]
     return Entity::Entity(id);

                             ^
entity_manager.cpp:19:29: note: for a function-style cast, remove the redundant ‘::Entity’
entity_manager.cpp:12:1: error: ‘Entity::Entity(unsigned int)’ is private
 Entity::Entity(unsigned id) : id(id) {}
 ^
entity_manager.cpp:19:29: error: within this context
     return Entity::Entity(id);

您的 friend 声明倒退了。您需要在 Entity 结构中包含此行:

friend class EntityManager;

尝试以下方法

struct Entity;

class EntityManager
{
public:
    Entity create();

private:
    Entity make_entity(unsigned index, unsigned generation);
};

struct Entity 
{
private:
    unsigned id;
    Entity(unsigned id);
    Entity();
    friend Entity EntityManager::make_entity(unsigned index, unsigned generation);
};

您的 friend 声明落后了。好友 class 包含可供好友 class.

使用的私有(and/or 受保护)成员
struct Entity 
{
    unsigned id;
private:
    Entity(unsigned id);
    Entity();
    friend class EntityManager;
};

好友声明需要放在Entityclass,而不是EntityManagerclass。否则,任何 class 都可以通过在声明中放置 friend class X 来访问另一个 class 的私有数据。希望共享其私有数据的 class 必须明确声明。