C++指向成员函数的指针
C++ pointers to member functions
我想在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_function
是itd->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;
}
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址