的私有构造函数,我有以下两类:无法访问朋友类
struct Entity
{
unsigned id;
Entity(unsigned id);
Entity();
};
class EntityManager
{
public:
Entity create();
...
private:
Entity make_entity(unsigned index, unsigned generation);
};
这在目前工作正常。问题是封装。我不想让类Entity
的直接创建。
因此,我的目标是使Entity
的构造函数为私有。然后,我可以(根据我的理解)通过制作Entity
a friend
的EntityManager
来保留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::Entity(id)
调用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);