通过添加新方法来发展类

Evolve class by adding new methods

本文关键字:新方法 添加      更新时间:2023-10-16

假设我有一些类

class A {
...
};

里面封装了一些变量和方法。我的问题是,如果类可以"学习"新方法 - 某些函数将新方法放入类体中。

例如,我有一个空类

class Draw {};

我的程序中的某些函数从文件中读取数据,并在此基础上绘制圆形,正方形等。是否可以将这些绘图方法放在 Draw 类主体中,以便它动态增长?

是的。

class Draw
{
public:
    ReturnType call(const std::string& methodName, ArgTypes args)
    {
       return methods[methodName](this, args);
    }
private:
    std::unordered_map<
       std::string,
       std::function<ReturnType(Draw*, ArgTypes)>
    > methods;
};

根据需要添加到methods

(我已经抽象ReturnTypeArgTypes;在那里选择你需要的东西。

"我的问题是,如果类可以"学习"新方法 - 某些函数将新方法放入类体内"的简单答案是否定的