【问题标题】:C++ pointers to member functions指向成员函数的 C++ 指针
【发布时间】:2012-11-30 09:08:36
【问题描述】:

我想在 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

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

提前谢谢!!

【问题讨论】:

  • 熟悉std::function可能会更好
  • 请出示parse_numberitd所属容器的声明。
  • 第一个调用(在 printf 中)返回一些连贯的东西(有一个 switch 案例,其中 parsing_function 被影响到“parse_function”并且。映射的所有元素 匹配 case1打印结果为 0x2ad9d65302e0,所有匹配 case2 的元素打印结果为 0x2ad9d65303b0。
  • 尝试删除int ret = (itd->second.*parse_function)(str, pts); 中的星号?
  • 您能否编辑您的问题以包含usable example

标签: c++ class function pointers


【解决方案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 类型,但它可能不是。并且 parse_function 必须定义为当前或封闭范围内的变量(第一种情况)或 Number 类的静态变量(第二种情况)。

所以你需要一些 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);

【讨论】:

  • itd->second 必须是 Number 类型...但它是! map<string, Number >::iterator itd = mapNumbers.begin();Argh...我不明白
  • @Jav 请在您的问题中包含此重要信息。
  • 谢谢!!!!这现在有效! (天哪:我还没想过这个,但现在我觉得很清楚了,txh)
  • @Jav 如果这解决了您的问题,请考虑accepting my answer。谢谢。
【解决方案2】:

您可以像这样定义指向函数的指针: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;
}

【讨论】:

  • 你在int(*f)() = &amp;func 后面漏掉了一个分号(很抱歉吹毛求疵):)
  • 指向函数的指针与指向 C++ 中的成员函数的指针非常不同。仔细阅读问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
相关资源
最近更新 更多