基于帖子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)}’
有谁知道错误是什么?