C++ understanding cocos2d-x use of function pointers

前端 未结 1 1047
死守一世寂寞
死守一世寂寞 2020-12-15 13:38

I am experimenting around with extending cocos2d-x CCMenuItem components and came across something I have not seen before in C++. It would be helpful if someone would elabor

1条回答
  •  春和景丽
    2020-12-15 14:13

    void (CCObject::*)(CCObject*) is a method pointer type (one type of pointer to member), not an ordinary function pointer. It's a pointer that can point to an instance method of the CCObject class that takes a parameter of CCObject* type. The type of class it's a method of is part of the pointer type (denoted by the CCObject::), similar to the parameters (because underneath, a pointer to the "current object" is a hidden parameter to all instance methods, this).

    The typedef simply defines SEL_MenuHandler to be a synonym for that method pointer type.

    To use a method pointer, you need to provide both an instance to act as this, as well as the arguments, using a syntax like this:

    CCObject* object;
    CCObject* anotherObject;
    SEL_MenuHandler methodPointer;
    (object->*methodPointer)(anotherObject);
    // or equivalently: ((*object).*methodPointer)(anotherObject);
    

    How would C++ handle this if the function was not passed by pointer. Is a function treated like an object with a copy constructor?

    In C/C++, it is not possible to have an expression of "function type" or "method type". Any time you try to get something of "function type", it is automatically converted to a "pointer to function" type.

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