简体   繁体   中英

c++ callback of a member function

#include<iostream>

class Bar;

class Foo{
public:
    void (Bar::*callback)(void);
    Bar* bar;
    Foo(Bar* bar, void (Bar::*cb)(void)){
        callback = cb;
    }
    void execute(){
        (bar->*callback); // commenting out this will make it compile
        // i want to execute callback here, but can't find a way to do it
    }
};

class Bar{
public:
    Foo *f;

    Bar(){
        f = new Foo(this, &Bar::func);
        f->execute();
    }

    void func(){ // this can't be static
        std::cout << "func executed" << std::endl;
    }
};

int main(){
    Bar b;

    return 0;
}

This is what i want to do, i need make a callback for example for a button. but i cant get call a member function pointer.

Or is another way i should rather use to get this functionality?

Edit: the error i am getting is "invalid use of non-static member function" Making the function static is not a option.

 (bar->*callback); 

You're not calling the function here, just dereferencing it:

 (bar->*callback)(); // ^^ 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM