纯C++下实现通过字符串创建不同的自定义类对象

纯C++下实现通过字符串创建不同的自定义类对象

#include <iostream>
#include <map>
#include <string>

using namespace std;

// 定义基类
class Base {
public:
    virtual void doSomething() = 0;
    virtual ~Base() {}
};

// 定义派生类A
class A : public Base {
public:
    void doSomething() {
        cout << "This is A." << endl;
    }
};

// 定义派生类B
class B : public Base {
public:
    void doSomething() {
        cout << "This is B." << endl;
    }
};

// 定义工厂类
class Factory {
public:
    // 注册类
    static void registerClass(const string& name, Base* obj) {
        classMap[name] = obj;
    }

    // 创建类
    static Base* createClass(const string& name) {
        if (classMap.find(name) != classMap.end()) {
            return classMap[name];
        }
        return nullptr;
    }

private:
    static map<string, Base*> classMap;
};

map<string, Base*> Factory::classMap;

// 注册类到工厂
void registerClasses() {
    Factory::registerClass("A", new A());
    Factory::registerClass("B", new B());
}

int main() {
    registerClasses();

    // 通过字符串实例化类对象
    string className = "A";
    Base* obj = Factory::createClass(className);
    if (obj != nullptr) {
        obj->doSomething();
    }

    className = "B";
    obj = Factory::createClass(className);
    if (obj != nullptr) {
        obj->doSomething();
    }

    return 0;
}









#include <iostream>  

#include <string>  

#include <map>  

  

// 基类  

class Base {  

public:  

    virtual void print() = 0; // 纯虚函数  

};  

  

// 子类1  

class Derived1 : public Base {  

public:  

    void print() override {  

        std::cout << "Derived1" << std::endl;  

    }  

};  

  

// 子类2  

class Derived2 : public Base {  

public:  

    void print() override {  

        std::cout << "Derived2" << std::endl;  

    }  

};  

  

// 根据字符串创建对象  

std::map<std::string, std::function<Base*()>> factory {  

    {"Derived1", []() -> Base* { return new Derived1; } },  

    {"Derived2", []() -> Base* { return new Derived2; } },  

};  

  

int main() {  

    std::string type = "Derived1"; // 这里我们使用字符串来决定创建哪种类型的对象  

    Base* obj = factory[type](); // 使用map中的函数创建对象  

    obj->print(); // 调用对象的print方法,输出"Derived1"  

    delete obj; // 不要忘记删除创建的对象!  

    return 0;  

}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九江在天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值