gpt4 book ai didi

c++ - 使用另一个类构造函数来初始化类

转载 作者:行者123 更新时间:2023-11-30 03:13:51 24 4
gpt4 key购买 nike

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

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

最佳答案

总之,你不能在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;
}

关于c++ - 使用另一个类构造函数来初始化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58368866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com