【发布时间】:2017-08-23 15:59:38
【问题描述】:
我的游戏引擎总共有三个类,一个抽象的 IComponent 类,其中所有组件都从它继承,一个组件类(在本示例中,我将使用 RenderComponent)和一个 ComponentManager。我希望 ComponentManager 类能够使用 RenderComponent 的构造函数,但我不希望任何其他类创建 RenderComponent 的实例,但我不想使用“朋友”,因为我希望客户用户组件继承来自 IComponent 并自动在 ComponentManager 中使用,而不允许实例化自己的。代码示例模糊地显示了我想要发生的行为:
class GameObject;
class IComponent
{
private:
IComponent() { }
~IComponent() { }
public:
GameObject* Parent;
}
class RenderComponent : IComponent
{
public:
RenderComponent() { }
~RenderComponent() { }
}
class ComponentManager
{
public:
ComponentManager() { }
~ComponentManager() { }
// normally this would be a template function, but for the sake of this example I will directly use RenderComponent
RenderComponent* CreateComponent()
{
// this would not throw a compiler error
return new RenderComponent();
}
}
int main()
{
ComponentManager manager;
// even though the constructor of RenderComponent is public, this would throw an error
RenderComponent* render = new RenderComponent();
// this however would work perfectly fine
RenderComponent* render = manager.CreateComponent();
}
重申一下,我希望它可以让用户在创建组件时付出最少的努力。当然,另一种选择是让两者的构造函数都公开,但拥有它,这样虽然你可以在任何你想要的地方创建一个组件,但它是无用的。
【问题讨论】:
-
您可以使用工厂模式来做到这一点,但不是您尝试的方式。
-
虽然我不知道在制作工厂模式时如何不使用“朋友”,但如果它解决了我的问题,我会切换到它。
-
您对为什么不想使用
friend的解释没有真正的意义。你能详细说明一下吗? -
我只是不希望用户每次制作自己的组件时都必须执行
friend class ComponentManager。我可以只公开构造函数/析构函数,但我也想限制用户实例化组件的能力。
标签: c++ inheritance components friend