Passing member function pointer to member object in c++

后端 未结 4 1207
一个人的身影
一个人的身影 2020-12-04 22:54

I have a problem with using a pointer to function in C++. Here is my example:

#include 

using namespace std;

class bar
{
public:
    void (         


        
4条回答
  •  死守一世寂寞
    2020-12-04 23:26

    As the error says, methods belong to the class, not to individual instances. For this reason pointers to free functions and pointers to non-static methods are completely different things. You'll also need an instance to call the method on.

    //declaring and taking the address of a foo's method 
    void (foo::*method)() = &foo::hello; //as the compiler nicely suggests
    
    //calling a function through pointer
    free_func();
    
    //calling a method through pointer
    foo instance;
    (instance.*method)();
    

    You can use libraries like Boost.Bind and Boost.Function (also in std::tr1 I think) to abstract away the difference and also bind an instance to the method:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    class foo
    {
    public:
        void hello(){cout << "hello" << endl;};
    };
    
    void byebye()
    {
        cout << "bye" << endl;
    }
    
    
    int main()
    {
        foo testFoo;
    
        boost::function helloFunc(boost::bind(&foo::hello, testFoo));
        boost::function byeFunc(byebye);
    
        helloFunc();
        byeFunc();
        return 0;
    }
    

提交回复
热议问题