[英]Cannot access private constructors of a Friend class
我有以下兩節課:
struct Entity
{
unsigned id;
Entity(unsigned id);
Entity();
};
class EntityManager
{
public:
Entity create();
...
private:
Entity make_entity(unsigned index, unsigned generation);
};
目前,這可以正常工作。 問題是封裝。 我不想允許直接創建Entity
類。
因此,我的目標是使Entity
的構造函數私有。 然后,我可以(根據我的理解)通過將Entity
成為EntityManager
的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);
};
這破壞了代碼。 我得到的錯誤是這個:
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::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;
朋友聲明需要進入Entity
類,而不是EntityManager
類。 否則,任何任意類都可以通過將friend class X
放置在其聲明中來訪問另一個類的私有數據。 希望共享其私有數據的類必須明確聲明。
嘗試以下
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
聲明向后。 友善類包含可以由友善類使用的私有(和/或受保護)成員。
struct Entity
{
unsigned id;
private:
Entity(unsigned id);
Entity();
friend class EntityManager;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.