C ++ /如何基于用户输入实例化对象

时间:2015-02-15 22:13:38

标签: c++

例如,如果用户输入字符串“modem”,是否有办法实例化类Modem的对象。

或者有一种更简单的方法可以做到这一点。

3 个答案:

答案 0 :(得分:3)

std::string strText = "modem";
CBase *pBase = nullptr;
if(strText == "modem")
    pBase = new CDervied1;
else
    pBase = new CDervied2;

答案 1 :(得分:1)

在这个例子中,我将使用工厂模式。见http://www.oodesign.com/factory-pattern.html

答案 2 :(得分:1)

使用std::map的方法是向每个子类添加静态成员函数create,例如

class CDerived1 : public CBase {
public:
    static CBase* create() {
        return new CDerived1;
    }
}

并有一个函数指针的映射:

typedef CBase*(create_function_t*)();
std::map<std::string, create_function_t > mapping = {
    {"modem", &CDerived1::create},
    ....
}

...

CBase* pBase = mapping[strText]();