根据构造函数中的参数创建内部对象?

时间:2016-01-27 05:44:58

标签: c++ inheritance polymorphism virtual multiple-inheritance

我有两个B和C类(都来自A类)一个名为H的类,它包含A或B.

代码:

class A  // abstract base class
{
  // bells and whistles
  // virtual fn 
     void fn() = 0 ; 
     protected:
         // some variables common to B and C
};

class B : public A  // inherit from A...
{
      B();
      fn(); // implement virtual function
      // bells and whistles
};

B::B() :A()
{
 // things
}

void B::fn()
{
 // things
}

// Class C : exactly the same as class B 


// Class H : holds B or C 
enum class CLASS_TYPE { TYPE_B, TYPE_C }

class H
{
   public:
      H(CLASS_TYPE type_);
      ~H();
   private: 
      A * _obj; 

};


H::H(CLASS_TYPE type_)
{
     switch(type_)
     {
     case CLASS_TYPE::B:
          _obj = new B();
          break;
     case CLASS_TYPE::C:
          _obj = new C();
          break;
     }
}

H::~H()
{
    delete _obj;// delete allocated object 
}

这是基于构造函数中的参数在类中创建内部对象的正确方法吗? 也是使用抽象基类,虚拟高效?这是大规模模拟程序的一部分,我想避免性能损失。

谢谢。 PS:我试图保持简单,如果需要更多信息请告诉我。

2 个答案:

答案 0 :(得分:3)

  

这是基于构造函数中的参数在类中创建内部对象的正确方法吗?

我的第一个倾向是摆脱enum。让类的用户构造一个对象并使用它来构造H

virtual成员函数clone()添加到A

更改构造函数以接受A const&。使用clone()成员函数在构造函数中创建输入对象的副本。

H中的成员变量更改为std::unique_ptr而不是原始指针。

这是我的建议:

class A 
{
   public:
      virtual A* clone() const = 0;
      virtual void fn() = 0 ; 
   protected:
};

class B : public A
{
   public:

      virtual A* clone() const
      {
         return new B;
      }

      B();
      virtual void fn();
};

B::B() : A()
{
}

void B::fn()
{
}

#include <memory> // of std::unique_ptr
class H
{
   public:

      H(A const& a);

      // No need to have an explicit destructor.
      // The compiler generated destructor will do just fine.
      // ~H();

   private: 
      std::unique_ptr<A> aPtr_;
};

H::H(A const& a) : aPtr_(a.clone())
{
}

答案 1 :(得分:0)