cod*_*nk1 5 c++ virtual constructor template-method-pattern
可能的重复:
在构造函数内调用虚函数
我有一个 Shape 类及其子类 Sphere :
//Shape :
class Shape
{
public:
Shape(const string& name);
virtual ~Shape();
virtual string getName();
protected:
string mName;
};
Shape::Shape(const string& name) : mName(name)
{
/*Some stuff proper to Shape*/
/*Some stuff proper to subclass (sphere)*/
/*Some stuff proper to Shape*/
}
Shape::~Shape(){}
string Shape::getName(){ return mName; }
//Sphere :
class Sphere : public Shape
{
public:
Sphere(const string& name, const float radius);
virtual ~Sphere();
virtual string getRadius();
protected:
float mRadius;
}
Sphere::Sphere(const string& name, const float radius) : Shape(name), mRadius(radius)
{
/*Some stuff*/
}
Sphere::~Sphere(){}
float Sphere::getRadius(){ return mRadius; }
Run Code Online (Sandbox Code Playgroud)
现在,我如何处理 Shape 构造函数中的子类内容?我可以诉诸 模板方法模式,但我将被迫在构造函数中调用纯虚函数;我尝试过,但编译器不喜欢它
编辑:
我选择将构造函数内容移到新方法“init”中,虚拟方法将是“subInit”:
//Shape :
class Shape
{
public:
Shape(const string& name);
virtual ~Shape();
virtual string getName();
virtual void init();
protected:
string mName;
virtual void subInit() = 0;
};
Shape::Shape(const string& name) : mName(name){}
Shape::~Shape(){}
string Shape::getName(){ return mName; }
void Shape::init()
{
/*Some stuff proper to Shape*/
/*Some stuff proper to subclass (sphere)*/
/*Call to the pure virtual function subInit*/
subInit();
/*Some stuff proper to Shape*/
}
//Sphere :
class Sphere : public Shape
{
public:
Sphere(const string& name, const float radius);
virtual ~Sphere();
virtual string getRadius();
protected:
float mRadius;
void subInit();
}
Sphere::Sphere(const string& name, const float radius) : Shape(name),mRadius(radius)
{}
Sphere::~Sphere(){}
float Sphere::getRadius(){ return mRadius; }
Sphere::subInit()
{
/*Some stuff previously in the constructor*/
}
Run Code Online (Sandbox Code Playgroud)
它基本上是模板方法模式
客户会写:
Shape* sphere = new Sphere();
sphere->init();
Run Code Online (Sandbox Code Playgroud)
然后我得到了答案:在构造函数中应用这种模式是不可能的,至少在 C++ 中是不可能的
Shape::Shape(const string& name) : mName(name)
{
/*Some stuff proper to Shape*/
/*Some stuff proper to subclass (sphere)*/
/*Some stuff proper to Shape*/
}
Run Code Online (Sandbox Code Playgroud)
子类特有的东西只有在子类存在之后才能运行,所以它应该放在子类的构造函数中。后面的内容可以进入子类构造函数调用的函数中。
Shape::Shape(const string& name) : mName(name)
{
/*Some stuff proper to Shape*/
}
void Shape::finishConstruction()
{
/*Some stuff proper to Shape*/
}
Sphere::Sphere(const string& name, const float radius)
: Shape(name), mRadius(radius)
{
/*Some stuff proper to subclass (sphere)*/
finishConstruction();
}
Run Code Online (Sandbox Code Playgroud)