Passing a pointer to a class member function as a parameter

只谈情不闲聊 提交于 2019-12-17 22:16:17

问题


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<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;
}

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

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

回答1:


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



回答2:


In addition to Snps's answer, you could also use a function wrapper from C++11 to store a lambda function:

#include <iostream>
#include <functional>

class test
{
  public:
   std::function<void ()> Func;
   void get_pc();
   void call_cb_func();
   void set_func(std::function<void ()> func);
};

void test::get_pc()
{
  std::cout << "PC" << std::endl;
}

void test::call_cb_func()
{
  Func();
}

void test::set_func(std::function<void ()> func)
{
  Func = func;
}

int main() {
  test t1;
  t1.set_func([&](){ t1.get_pc(); });
  t1.call_cb_func();
}


来源:https://stackoverflow.com/questions/18145874/passing-a-pointer-to-a-class-member-function-as-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!