【发布时间】:2012-12-04 16:14:05
【问题描述】:
我希望有一个类层次结构,并且只能在工厂内部从它创建对象。
例子:
class Base
{
protected:
Base(){};
virtual void Init(){};
friend class Factory;
};
class SomeClass : public Base
{
public://I want protected here! Now it's possible to call new SomeClass from anywhere!
SomeClass(){};
void Init(){};
};
class Factory
{
public:
template<class T>
T* Get()
{
T* obj = new T();
obj->Init();
return obj;
}
};
int main()
{
Factory factory;
SomeClass *obj = factory.Get<SomeClass>();
}
我的问题是我希望能够仅从 Factory 生成对象,但我不想在从 Base 派生的每个类中声明 friend class Factory。
有没有办法在派生类中传播朋友?有没有其他方法可以实现这种行为?
【问题讨论】:
-
你不能继承
friendship。看到这个答案:stackoverflow.com/questions/13844129/… -
请注意,
protected的限制仅比public稍微严格一些。任何人都可以从SomeClass继承并提供进入其protected成员的途径。