我编写了一个小程序,试图将指向类的成员函数的指针传递给另一个函数。你能帮我吗,我哪里出错了..?
#include<iostream>
using namespace std;
class test{
public:
typedef void (*callback_func_ptr)();
callback_func_ptr cb_func;
void get_pc();
void set_cb_ptr(void * ptr);
void call_cb_func();
};
void test::get_pc(){
cout << "PC" << endl;
}
void test::set_cb_ptr( void *ptr){
cb_func = (test::callback_func_ptr)ptr;
}
void test::call_cb_func(){
cb_func();
}
int main(){
test t1;
t1.set_cb_ptr((void *)(&t1.get_pc));
return 0;
}
当我尝试编译时出现以下错误。
error C2276: '&' : illegal operation on bound member function expression
最佳答案
您不能将函数指针强制转换为 void*
。
如果你想要一个函数指针指向一个成员函数你必须声明类型为
ReturnType (ClassType::*)(ParameterTypes...)
此外,您不能声明指向绑定(bind)成员函数的函数指针,例如
func_ptr p = &t1.get_pc // Error
相反,您必须得到这样的地址:
func_ptr p = &test::get_pc // Ok, using class scope.
最后,当您调用指向成员函数的函数指针时,您必须使用该函数所属的类的实例来调用它。例如:
(this->*cb_func)(); // Call function via pointer to current instance.
这是应用了所有更改的完整示例:
#include <iostream>
class test {
public:
typedef void (test::*callback_func_ptr)();
callback_func_ptr cb_func;
void get_pc();
void set_cb_ptr(callback_func_ptr ptr);
void call_cb_func();
};
void test::get_pc() {
std::cout << "PC" << std::endl;
}
void test::set_cb_ptr(callback_func_ptr ptr) {
cb_func = ptr;
}
void test::call_cb_func() {
(this->*cb_func)();
}
int main() {
test t1;
t1.set_cb_ptr(&test::get_pc);
t1.call_cb_func();
}
关于c++ - 将指向类成员函数的指针作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18145874/