无法访问Friend类的私有构造函数
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(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;
};
相关文章:
- 固有构造函数的字符和访问级别
- C++:为什么无法在派生类中访问受保护的构造函数?
- 使用 CTRP 时,是否访问访问父构造函数 UB 中的子属性?
- c++ cuda:cudaMalloc在构造函数之外的托管访问
- 使用值初始化访问构造函数?
- 限制variadic模板类中的构造函数访问
- 构造函数无法访问继承类私有 int
- 从派生类访问模板基类的构造函数
- 如何在构造函数中访问类变量以分配它们,而无需在C++中使用此指针
- 访问在构造函数期间创建的值 - C++
- 从析构函数访问模板类构造函数的参数,可以吗?
- 仅当构造函数具有参数时,C++ 公共成员才能访问
- 正确的友元定义,以授予 std::map 对私有默认构造函数的访问权限
- 在派生类的构造函数初始化中无法访问受保护的函数
- 是否可以从 C++ 中的构造函数访问对象名称?
- 从构造函数访问值
- 聚合初始化不支持构造函数访问
- 无法从构造函数访问私有变量 - 不在范围(C )中
- c++工厂.子构造函数不能从父构造函数访问
- 如何通过类构造函数访问私有静态成员变量