是否可以在构造函数中使用模板方法模式?

时间:2013-01-27 21:17:11

标签: c++ constructor virtual template-method-pattern

  

可能重复:
  Calling virtual functions inside constructors

我有一个类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; }

现在,我如何处理Shape构造函数中的子类?我可以诉诸template method pattern,但我会被迫在构造函数中调用纯虚函数;我试过,编译器不喜欢它

修改

我选择在一个新方法'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*/
    }

它基本上是模板方法模式

客户将写:

Shape* sphere = new Sphere();
sphere->init();

然后我得到了答案:不可能在构造函数中应用此模式,至少在C ++中

1 个答案:

答案 0 :(得分:1)

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(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();
}