【问题标题】:How do I redefine a class's function outside of the class如何在类之外重新定义类的功能
【发布时间】:2017-10-07 12:12:02
【问题描述】:
class Function
{
public:
    std::string Name;
    void call(std::string x);

    Function(std::string Nam)
    {
        Name = Nam;
    }
};

std::vector<Function> funcs;

void Load_FuncLib()
{
    Function print("print");
    Function add("add");

    print.call(std::string x)
    {
        std::cout<< x <<"\n";
    }
    add.call(std::string x)
    {
        std::cout<< std::stoi(x) + std::stoi(x) << "\n";
    }

    funcs.push_back(print);
    funcs.push_back(add);

    funcs.at(0).call("Hello world");
}

我希望它运行函数print.call("Hello world");,但它不起作用,因为我不知道如何设置已声明的函数,也不知道如何使用向量调用它。

【问题讨论】:

    标签: c++ class vector std void


    【解决方案1】:

    您很可能想要实现这样的目标?

    #include <unordered_map>
    #include <iostream>
    #include <string>
    #include <functional>
    
    int main() {
        std::unordered_map<std::string, std::function<void (const std::string&)>> funcs;
    
        funcs["print"] = [](const std::string& str) {
            std::cout << str << '\n';
        };
    
        funcs["add"] = [](const std::string& str) {
            int i = std::stoi(str);
            std::cout << i + i << '\n';
        };
    
        funcs["print"]("Hello, World!");
        funcs["add"]("12");
    }
    

    https://ideone.com/Ke4aEK

    您可以随时使用另一个函数重置哈希映射的某个值。 此外,根据您的需要,您可以使用 std::function 或仅使用普通函数指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 2011-12-18
      • 2019-04-23
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多