使用另一个类构造函数初始化类

时间:2019-10-14 00:40:48

标签: c++

我想创建一个类对象,该对象将根据给定参数使用不同的类构造函数。这是我到目前为止尝试过的。

class A{
    public:
        A(int x){
            if (x == 1){
                B();    //Initialize object with B constructor
            else {
                C();    //Initialize object with C constructor
            }
        }
};

class B : public A{
    public:
        B(){
            //initialize
        }
};

class C : public A{
    public:
        C(){
            //initialize
        }
};

int main(){
    A obj(1); //Initialized with B constructor
    return 0;
}

1 个答案:

答案 0 :(得分:2)

总之,您无法在C ++中做到这一点。典型的解决方案是着眼于工厂模式。

class A {
public:
  virtual ~A() {}
  A() = default;
};
class B : A {
public:
  B() = default;
};
class C : A {
public:
  C() = default;
};

enum class Type 
{
  A,
  B, 
  C
};

class Factory
{
public:

  A* operator (Type type) const
  {
    switch(type)
    {
    case Type::A: return new A;
    case Type::B: return new B;
    case Type::C: return new C;
    default: break;
    }
    return nullptr; 
  }
};

int main()
{
  Factory factory;
  A* obj = factory(Type::B); //< create a B object

  // must delete again! (or use std::unique_ptr)
  delete obj;
  return 0;
}