2015-12-08 141 views
1

的私有构造函数,我有以下两类:无法访问朋友类

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 friendEntityManager来保留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); 

回答

6

你有friend声明倒退。你需要有这条线在Entity结构:

friend class EntityManager; 
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); 
}; 
0

你有你的friend声明落后。好友类包含可以被友好类使用的私人(和/或受保护)成员。

struct Entity 
{ 
    unsigned id; 
private: 
    Entity(unsigned id); 
    Entity(); 
    friend class EntityManager; 
}; 
2

friend声明需要在Entity类,而不是EntityManager类中去。否则,只要将friend class X置于其声明中,任何类都可以访问另一个类的私有数据。希望分享其私有数据的类必须明确声明。