C++ How to make function pointer to class method

前端 未结 3 989
时光说笑
时光说笑 2020-12-04 02:18

I\'m having trouble making a function pointer to a class method. I made a function pointer to a non-class method and it works fine.

int foo(){
    return 5;
         


        
相关标签:
3条回答
  • 2020-12-04 02:59

    A member function is quite a bit different from an ordinary function, so when you want to point to a member function you need a pointer-to-member-function, not a mere pointer-to-function. The syntax for a pointer-to-member-function includes the class that the member function is a member of:

    void (Game::*mptr)();
    

    This defines a pointer-to-member-function named mptr that holds a pointer to a member function of the class Games that takes no arguments and returns nothing. Contrast that with an ordinary function pointer:

    void (*ptr)();
    

    This defined a pointer-to-function named ptr that holds a pointer to a function that takes no arguments and returns nothing.

    0 讨论(0)
  • 2020-12-04 03:09

    1- Use the following syntax to point to a member function:

    return_type (class_name::*ptr_name) (argument_type) = &class_name::function_name;
    

    2- keep in mind to have a pointer to member function you need to make it public.

    in your case:

    class Game
    {
    
    public:
    
        Game(){}
    
        void print() { 
          //todo ...
        }
    
    
    };
    // Declaration and assignment
    void (Game::*method_ptr) () = &Game::print;
    
    0 讨论(0)
  • 2020-12-04 03:14

    Just found out you can do

    #include <functional>
    #include <cassert>
    
    using namespace std;
    
    struct Foo {
       int x;
       int foo() { return x; }
    };
    
    int main() {
      function<int(Foo&)> f = &Foo::foo;
      Foo foo = { 3 };
      assert(f(foo) == 3);
      foo.x = 5;
      assert(f(foo) == 5);
    }
    

    std::mem_fn() might work too: https://en.cppreference.com/w/cpp/utility/functional/mem_fn

    0 讨论(0)
提交回复
热议问题