How to invoke pointer to member function when it's a class data member?

后端 未结 3 395
盖世英雄少女心
盖世英雄少女心 2020-12-06 02:14
struct B
{
  void (B::*pf)(int, int);  // data member
  B () : pf(&B::foo) {}
  void foo (int i, int j) { cout<<\"foo(int, int)\\n\"; } // target method
};         


        
相关标签:
3条回答
  • 2020-12-06 02:32

    Like this:

    (obj.*obj.pf)(0, 1);
    

    Member access (.) has a higher precedence than a pointer to member operator so this is equivalent to:

    (obj.*(obj.pf))(0, 1);
    

    Because function call also has higher precedence than a pointer to member operator, you can't do:

    obj.*obj.pf(0, 1) /* or */ obj.*(obj.pf)(0, 1)
    

    As that would be equivalent to:

    obj.*(obj.pf(0, 1)) // grammar expects obj.pf to be a callable returning a
                        // pointer to member
    
    0 讨论(0)
  • 2020-12-06 02:41

    The syntax is quite unnatural but a consequence of C++ precedence rules...

    (obj.*obj.pf)(1, 2);
    
    0 讨论(0)
  • 2020-12-06 02:42

    pf is a method pointer, and you want to invoke the method it points to, so you have to use

    (obj.*obj.pf)(1, 2);
    

    It says the object obj you invoke the method pointed by pf

    See result here :

    http://ideone.com/p3a5G

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