gpt4 book ai didi

c++ - 根据值实例化不同对象类型的最佳方法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:43:50 25 4
gpt4 key购买 nike

<分区>

我将把我的数百个类的问题简化为两个类,并尝试解释我的意思:

class Base {
};
class A: public Base {
};
class B: public Base{
};

static Base* foo (int bar){

switch (bar) {
case 0:
return new A();
break;
case 1:
return new B();
break;
default:
return new Base();
}
}

我想根据bar的值来实例化对象。我只是觉得 switch-case 不是 C++ 中为 Base 的更多继承者这样做的最佳方式。

编辑:使用 std::map 方法我想到了这个:

struct Dictionary {
typedef Base* (Dictionary::*FunctionPointer)(void);
std::map <int, FunctionPointer> fmap;

Dictionary() {
fmap.insert(std::make_pair(0, new A()));
fmap.insert(std::make_pair(1, new B()));
}

Base* Call (const int i){
FunctionPointer fp = NULL;
fp = fmap[i];
if (fp){
return (this->*fp)();
} else {
return new Base();
}
}
};

static Dictionary dictionary;

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