把类成员改成指针,将指向类成员函数的指针作为参数传递

I have written a small program where I am trying to pass a pointer to member function of a class to another function. Can you please help me and where I am going wrong..?

#include

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;

}

I get the following error when I try to compile it.

error C2276: '&' : illegal operation on bound member function expression

解决方案

You cannot cast a function pointer to void*.

If you want a function pointer to point to a member function you must declare the type as

ReturnType (ClassType::*)(ParameterTypes...)

Further you cannot declare a function pointer to a bound member function, e.g.

func_ptr p = &t1.get_pc // Error

Instead you must get the address like this:

func_ptr p = &test::get_pc // Ok, using class scope.

Finally, when you make a call to a function pointer pointing to a member function, you must call it with an instance of the class that the function is a member of. For instance:

(this->*cb_func)(); // Call function via pointer to current instance.

Here's the full example with all changes applied:

#include

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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值