C++指向成员函数的指针

C++ pointers to member functions

本文关键字:指针 函数 成员 C++      更新时间:2023-10-16

我想在C++中使用指向成员函数的指针,但它不起作用:

指针声明:

int (MY_NAMESPACE::Number::*parse_function)(string, int);

指针分配:

parse_function = &MY_NAMESPACE::Number::parse_number;

这个调用工作得很好(itd 是映射元素的迭代器):

printf("%st%pn",itd->first.c_str(),itd->second.parse_function);

但是这个不起作用:

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

我不明白为什么...

提前感谢!!

int (MY_NAMESPACE::Number::*parse_function)(string, int);

这说明,parse_function是指向类 Number 的成员函数的指针。

这个调用工作得很好(itd 是映射元素的迭代器):

printf("%st%pn",itd->first.c_str(),itd->second.parse_function);

由此我们可以看出parse_functionitd->second的成员,不管这是什么。

对于此电话

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

或此电话

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

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

所以你需要一些Number并应用parse_function

Number num;
(num.*(itd->second.parse_function))(str, pts);

或带有指针

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

更新

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

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

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

int(*func_ptr)();
func_ptr = &myFunction;

我可能只是在今天早上没有意识到你的代码,但问题可能是parse_function是一个指针,但你却像itd->second.*parse_function一样调用它。指针是用->*调用的,所以试着做itd->second->parse_function

可能无法解决任何问题,我似乎真的无法抓住您的代码。发布更多信息,很难从两行代码中分辨出来。


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

int func()
{
    cout << "Hello" << endl;
    return 0;
}
void cb(int(*f)())
{
    f();
}
int main()
{
    int(*f)() = &func;
    cb(f);
    return 0;
}