我有以下两个类:
struct Entity
{
unsigned id;
Entity(unsigned id);
Entity();
};
class EntityManager
{
public:
Entity create();
...
private:
Entity make_entity(unsigned index, unsigned generation);
};
此刻此工作正常。问题是封装。我不想允许直接创建类Entity
。
因此,我的目标是使Entity
的构造函数成为私有的。然后我可以(根据我的理解)通过EntityManager
Entity
friend
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);
};
中的mantain功能。
所以做出改变就是结果:
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);
,但后来又出现了另一个错误:
<h:outputScript name="charts/charts.js" library="primefaces" />
<h:outputStylesheet name="charts/charts.css" library="primefaces" />
答案 0 :(得分:6)
您向前发送friend
声明。您需要在Entity
结构中包含此行:
friend class EntityManager;
答案 1 :(得分:2)
朋友声明需要进入Entity
课程,而不是EntityManager
课程。否则,任何类都可以通过在其声明中放置friend class X
来访问另一个类的私有数据。希望共享其私有数据的类必须明确声明。
答案 2 :(得分:0)
尝试以下
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);
};
答案 3 :(得分:0)
您向前发送了friend
声明。友谊类包含可由专业人士使用的私人(和/或受保护)成员。
struct Entity
{
unsigned id;
private:
Entity(unsigned id);
Entity();
friend class EntityManager;
};