C++;指向成员函数的指针 我想在C++中使用指针到成员函数,但它不起作用: int ret = (itd->second.*parse_function)(str, pts); $ error: 'parse_function' was not declared in this scope

C++;指向成员函数的指针 我想在C++中使用指针到成员函数,但它不起作用: int ret = (itd->second.*parse_function)(str, pts); $ error: 'parse_function' was not declared in this scope,c++,class,function,pointers,C++,Class,Function,Pointers,指针声明: int (MY_NAMESPACE::Number::*parse_function)(string, int); 指针分配: parse_function = &MY_NAMESPACE::Number::parse_number; 此调用非常有效(itd是映射元素的迭代器): 但这个不起作用: int ret = (itd->second.*parse_function)(str, pts); $ error: 'parse_function' was not 

指针声明:

int (MY_NAMESPACE::Number::*parse_function)(string, int);
指针分配:

parse_function = &MY_NAMESPACE::Number::parse_number;
此调用非常有效(itd是映射元素的迭代器):

但这个不起作用:

int ret = (itd->second.*parse_function)(str, pts);
$ error: 'parse_function' was not declared in this scope
这一个也不是

int ret = (itd->second.*(MY_NAMESPACE::Number::parse_function))(str, pts);
$ [location of declaration]: error: invalid use of non-static data member 'MY_NAMESPACE::Number::parse_function'
$ [location of the call]: error: from this location
我不明白为什么


提前谢谢

您可以定义指向以下函数的指针:
type(*variable)(=&function
例如:

int(*func_ptr)();
func_ptr = &myFunction;
今天早上我可能没有意识到您的代码,但问题可能是
parse\u function
是一个指针,而您调用它就像
itd->second.*parse\u function
。 指针是用
->*
调用的,所以请尝试执行
itd->second->parse_函数

可能无法修复任何东西,但我似乎无法真正理解您的代码。 发布更多信息,很难从两行代码中分辨出来


下面是一个关于如何在实际代码中使用它的示例,这个示例仅使用指针和参数通过
cb()
调用
func()

int func()
{
    cout << "Hello" << endl;
    return 0;
}

void cb(int(*f)())
{
    f();
}

int main()
{
    int(*f)() = &func;
    cb(f);
    return 0;
}
int func()
{
库特
这表明,
parse_function
是指向类
Number
的成员函数的指针

此调用非常有效(itd是映射元素的迭代器):

printf(“%s\t%p\n”,itd->first.c_str(),itd->second.parse_函数);

从这里我们可以看到,
parse_function
itd->second
的成员,不管这是什么

打这个电话

int ret = (itd->second.*parse_function)(str, pts);
int ret = (itd->second.*(MY_NAMESPACE::Number::parse_function))(str, pts);
还是这个电话

int ret = (itd->second.*parse_function)(str, pts);
int ret = (itd->second.*(MY_NAMESPACE::Number::parse_function))(str, pts);

若要成功,
itd->second
必须是
Number
类型,它可能不是。parse_函数必须定义为当前或封闭范围内的变量(第一种情况)或类号的静态变量(第二种情况)

所以您需要一些
数字
,并对其应用
解析函数

Number num;
(num.*(itd->second.parse_function))(str, pts);
或者用指针

Number *pnum;
(pnum->*(itd->second.parse_function))(str, pts);
更新

由于
itd->second
是一个数字,因此必须应用
parse_函数
,它是它的成员,如下所示

int ret = (itd->second.*(itd->second.parse_function))(str, pts);

最好熟悉std::function请显示
parse_number
的声明以及
itd
所属的容器的声明。第一个调用(在printf中)返回一致的内容(存在一种切换情况,解析_函数会影响到“parse_function”和。匹配案例1的地图所有元素打印结果为0x2AD9D653020,匹配案例2的地图所有元素打印结果为0x2ad9d65303b0。尝试删除
int ret=(itd->second.*parse_function)(str,pts);
中的星号。你能编辑你的问题以包含一个吗?你在
int(*f)()之后漏掉了一个分号=和Func < /代码>(对不起NoTrink):函数指针与C++中的指针到成员函数非常不同。仔细阅读问题>代码> ITD- >第二版/代码>必须是“代码>号码<代码>……但是它是!<代码> MAP:迭代器ITD= MaMeNo.SKEN()
Argh……我不知道understand@Jav请在你的问题中包含这些重要的信息。谢谢!!!现在生效了!(OMG:我还没想好,但是现在我很清楚,TXH)JAV。如果这解决了你的问题,考虑一下。谢谢。