我想创建一个父类Base
,它的子类为Derived1
,Derived2
等工厂。Base
的构造函数及其所有派生类应该是私有的。我试着这样做:
base.h:
class Derived1;
class Base
{
protected:
Base ();
public:
Base *createDerived1 ();
}
#include "derived1.h"
derived1.h:
#include "base.h"
class Derived1 : public Base
{
friend class Base;
private:
Derived1 ();
}
derived1.cpp:
Derived1::Derived1 ()
: Base ()
{
}
base.cpp:
Base *Base::createDerived1 ()
{
return new Derived1 (); // error C2248: 'Derived1::Derived1' : cannot access private member declared in class 'Derived1'
}
但是,我无法访问工厂内的私有构造函数,尽管声明Base
是Derived1
的朋友类。我做错了什么,或者没有可能让父类成为朋友,我应该将Derived
类的构造函数公开?
答案 0 :(得分:1)
以下代码适用于我:
//B.h
class D;
class B{
protected:
B(){}
public:
static B* f();
};
//D.h
class D: public B{
friend class B;
private:
D():B(){}
};
//B.cpp
B* B::f(){
D *d=new D;
return d;
}
您的一个错误由另一个回复标识。另一个是工厂方法应该是static
,因为由于它有私有构造函数,你将无法创建Base
个对象。
答案 1 :(得分:0)
我写道,这确实是一个愚蠢的错误:
Base *createDerived1 ()
{
return new Derived1 (); // error C2248: 'Derived1::Derived1' : cannot access private member declared in class 'Derived1'
}
而不是
Base *Base::createDerived1 ()
{
return new Derived1 (); // everything fine
}
当然,无法从全局范围访问私有构造函数。