How do I call a pointer-to-member-function?

前端 未结 4 1600
南旧
南旧 2020-12-01 15:12

I\'m getting a compile error (MS VS 2008) that I just don\'t understand. After messing with it for many hours, it\'s all blurry and I feel like there\'s something very obvio

相关标签:
4条回答
  • 2020-12-01 15:33

    p->pfn is a function pointer. You need to use * to make it function. Change to

    (*(p->pfn))(val)
    
    0 讨论(0)
  • 2020-12-01 15:35

    Try

    return (this->*p->pfn)(val);
    
    0 讨论(0)
  • 2020-12-01 15:41

    Just to chime in with my own experience, I've come across an error in g++ caused by this statement:

      (this -> *stateHandler)() ;
    

    Where stateHandler is a pointer to a void member function of the class referenced by *this. The problem was caused by the spaces between the arrow operator. The following snippet compiles fine:

    (this->*stateHandler)() ;
    

    I'm using g++ (GCC) 4.4.2 20090825 (prerelease). FWIW.

    0 讨论(0)
  • 2020-12-01 15:46

    p->pfn is a pointer of pointer-to-member-function type. In order to call a function through such a pointer you need to use either operator ->* or operator .* and supply an object of type C as the left operand. You didn't.

    I don't know which object of type C is supposed to be used here - only you know that - but in your example it could be *this. In that case the call might look as follows

    (this->*p->pfn)(val)
    

    In order to make it look a bit less convoluted, you can introduce an intermediate variable

    PFN pfn = p->pfn;
    (this->*pfn)(val);
    
    0 讨论(0)
提交回复
热议问题