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

时间:2012-11-30 09:08:37

标签: c++ class function pointers

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

指针声明:

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

指针分配:

parse_function = &MY_NAMESPACE::Number::parse_number;

这个调用完美无缺(itd是地图元素的迭代器):

printf("%s\t%p\n",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

我不明白为什么......

提前thx !!

2 个答案:

答案 0 :(得分:1)

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

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

  

这个调用完美无缺(itd是地图元素的迭代器):

printf("%s\t%p\n",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类型,而大概不是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); ,这是成员,就像这样

{{1}}

答案 1 :(得分:0)

您可以定义指向函数的指针,如下所示: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;
}