gpt4 book ai didi

c++ - 如何通过名称调用函数。使用 STL::map 和 Class 的方法

转载 作者:行者123 更新时间:2023-11-28 03:06:45 24 4
gpt4 key购买 nike

基于帖子How to call a function by its name (std::string) in C++? , 尝试使用 CLASS 制作版本,但我的方法不起作用。

class A {
public:
int add(int i, int j) { return i+j; }
int sub(int i, int j) { return i-j; }
};

typedef int (*FnPtr)(int, int);

int main(int argc, char* argv[]) {

// initialization:
std::map<std::string, FnPtr> myMap;
A a;
myMap["add"] = a.add;
myMap["sub"] = a.sub;

返回这个错误:

main.cpp:31:22: error: cannot convert ‘A::add’ from type ‘int (A::)(int, int)’ to type ‘std::map<std::basic_string<char>, int (*)(int, int)>::mapped_type {aka int (*)(int, int)}’
main.cpp:32:22: error: cannot convert ‘A::sub’ from type ‘int (A::)(int, int)’ to type ‘std::map<std::basic_string<char>, int (*)(int, int)>::mapped_type {aka int (*)(int, int)}’

有谁知道错误是什么?

最佳答案

至少正如您所展示的那样,您的A 类 只提供了问题。如果你把它变成一个命名空间,事情会容易很多。

namespace A {
int add(int i, int j) { return i+j; }
int sub(int i, int j) { return i-j; }
};

typedef int (*FnPtr)(int, int);

int main(int argc, char* argv[]) {
std::map<std::string, FnPtr> myMap;
myMap["add"] = A::add;
myMap["sub"] = A::sub;
// ...

这样,addsub 就不是成员函数,因此不会出现类型不匹配的情况。至少如图所示,A 的实例除了调用 addsub 之外没有提供任何功能,因此命名空间在消除问题。

关于c++ - 如何通过名称调用函数。使用 STL::map 和 Class 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19480281/

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