You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QT项目中基于示例实现工厂方法模式及QMap函数指针咨询

在Qt项目中实现工厂方法模式(结合QMap与函数指针)

最近我在Qt项目里折腾工厂方法模式,参考了C++工厂模式的示例后,打算结合QMap来管理创建函数的指针,不过过程中遇到了一些相关问题,先贴出我目前写的代码片段:

#include <QCoreApplication>
#include <QDebug>

class IAnimal {
public:
    virtual int GetNumberOfLegs() const = 0;
    virtual void Speak() = 0;
    virtual void Free() = 0;
};

typedef IAnimal* (__stdcall *CreateAnimalFn)(void);

// IAnimal 实现类
class Cat : public IAnimal {
public:
    int GetNumberOfLegs() const { return 4; }
    void Speak() { qDebug() << "Meow~"; }
    void Free() { delete this; }
};

如果要把工厂类和QMap结合起来管理不同动物的创建逻辑,通常会这么写:

class AnimalFactory {
private:
    QMap<QString, CreateAnimalFn> m_creatorMap;
public:
    AnimalFactory() {
        // 注册猫的创建函数到Map中
        m_creatorMap.insert("Cat", &CreateCat);
    }

    IAnimal* CreateAnimal(const QString& animalType) {
        if (m_creatorMap.contains(animalType)) {
            return m_creatorMap[animalType]();
        }
        qDebug() << "Unknown animal type:" << animalType;
        return nullptr;
    }

    // 符合函数指针约定的创建函数
    static IAnimal* __stdcall CreateCat() {
        return new Cat();
    }
};

这里有几个需要注意的细节:

  • 函数指针的调用约定(__stdcall)要全程保持一致,不然容易出现调用栈错误
  • QMap的键可以根据需求用字符串、枚举或者其他类型,只要能唯一标识动物类型就行
  • 一定要在Free()方法里正确释放对象,避免内存泄漏

内容的提问来源于stack exchange,提问作者Agrowal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:48:56