Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

c++ - Passing a pointer to a class member function as a parameter

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...