我有一个类定义为
class modify_field
{
public:
std::string modify(std::string str)
{
return str;
}
};
有什么方法可以将此函数名称存储在 main 函数的字符串中,然后调用它。 我试过了,但没用。
int main()
{
modify_field mf;
std::string str,str1,str2;
str = fetch_function_name(); //fetch_function_name() returns string modify
str2 = "check";
cout << str; //prints modify
str1 = str + "(" +str2 + ")";
mf.str1();
}
我知道这是错误的。但我只想知道是否有任何方法可以使用变量调用函数名。
最佳答案
这在 C++ 中是不可能直接实现的。 C++ 是一种编译语言,因此函数和变量的名称不存在于可执行文件中 - 因此代码无法将您的字符串与函数名称相关联。
您可以通过使用函数指针获得类似的效果,但在您的情况下,您还尝试使用成员函数,这会使事情变得有点复杂。
我会举一个小例子,但想在我花 10 分钟写代码之前得到答案。
编辑:这里有一些代码来说明我的意思:
#include <algorithm>
#include <string>
#include <iostream>
#include <functional>
class modify_field
{
public:
std::string modify(std::string str)
{
return str;
}
std::string reverse(std::string str)
{
std::reverse(str.begin(), str.end());
return str;
}
};
typedef std::function<std::string(modify_field&, std::string)> funcptr;
funcptr fetch_function(std::string select)
{
if (select == "forward")
return &modify_field::modify;
if (select == "reverse")
return &modify_field::reverse;
return 0;
}
int main()
{
modify_field mf;
std::string example = "CAT";
funcptr fptr = fetch_function("forward");
std::cout << "Normal: " << fptr(mf, example) << std::endl;
fptr = fetch_function("reverse");
std::cout << "Reverse: " << fptr(mf, example) << std::endl;
}
当然,如果您想将函数存储在 map<std::string, funcptr>
中,那么这是完全可能的。
关于c++ - 使用包含函数名称的字符串调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18442101/