如何在 class 之外重新定义 class 的函数

How do I redefine a class's function outside of the class

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"); 但它不会工作,因为我不知道如何设置一个已经声明的函数,也不知道如何调用它使用向量。

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

#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 或仅使用普通函数指针。