gpt4 book ai didi

c++ - 通过添加新方法来发展类

转载 作者:行者123 更新时间:2023-11-30 03:53:45 26 4
gpt4 key购买 nike

假设我有一些课

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;
};

根据需要添加到方法

(我已经抽象掉了 ReturnTypeArgTypes;在那里选择你需要的。)

关于c++ - 通过添加新方法来发展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29966098/

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