C++ Call Pointer To Member Function

后端 未结 4 1208

I have a list of pointers to member functions but I am having a difficult time trying to call those functions... whats the proper syntax?

typedef void (Box::         


        
相关标签:
4条回答
  • 2020-11-27 19:30

    From my "award winning" ;-) answer about delegates (available at https://stackoverflow.com/questions/9568150/what-is-a-c-delegate/9568226#9568226) :

    Typedef the pointer to member function like this:

    typedef void (T::*fn)( int anArg );
    

    Declare one like this:

    fn functionPtr = &MyClass::MyFunction
    

    Call it like this:

    (MyObject.*functionPtr)( argument );
    
    0 讨论(0)
  • 2020-11-27 19:32

    Calling a member function through a pointer to member function has a particular syntax:

    (obj.*pmf)( params );   //  Through an object or reference.
    (ptr->*pmf)( params );  //  Through a pointer.
    

    Although ->* can be overridden, it isn't in the standard library iterators (probably because it would require overrides for every possible function type). So if all you've got is an iterator, you'll have to dereference it and use the first form:

    ((*iter).*pmf)( params );
    

    On the other hand, iterating over a the pointer to members themselves doesn't have this problem:

    (objBox.*(*i))( params );   //  If objBox is an object
    (ptrBox->*(*i))( params );  //  If ptrBox is a pointer
    

    (I don't think you need the parentheses around the *i, but the pointer to member syntax is already special enough.)

    0 讨论(0)
  • 2020-11-27 19:37

    Pointers to non-static members are a unique beast with unique syntax.

    Those functions need to be supplied a this pointer, so you must have the Box pointer handy that will be used as this.

    (box->*h)(xPos, yPos, width, height);
    
    0 讨论(0)
  • 2020-11-27 19:41

    Your attempt to get a member function pointer through an object betrays a misunderstanding. Member function pointers do not include a pointer to the object you call them on. You have to provide such a pointer at the point of the call.

    As many have pointed out, the syntax for a member function call is either:

     obj.*funcptr(args);
    

    or

     objptr->*funcptr(args);
    

    In the example you've given, it sounds like what you really need is a virtual function. You have a standard operation (detecting wether or not an object intersects with a box) that needs to be called on many different types of objects, the type of which can't be known at compile time. This is a job that is cut out for virtual functions.

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