我正在嘗試擴展cocos2d-x CCMenuItem組件,並遇到了一些我在C++中沒見過的東西。這將是有益的,如果有人對正在發生的事情與他們的函數指針聲明闡述C++瞭解cocos2d-x使用函數指針
對於大多數的cocos2d-x的對象的基類是CCObject它具有以下定義
class CC_DLL CCObject : public CCCopying
{
public:
// Code omitted
};
// The part in which I have a question about
typedef void (CCObject::*SEL_SCHEDULE)(float);
typedef void (CCObject::*SEL_CallFunc)();
typedef void (CCObject::*SEL_CallFuncN)(CCNode*);
typedef void (CCObject::*SEL_CallFuncND)(CCNode*, void*);
typedef void (CCObject::*SEL_CallFuncO)(CCObject*);
typedef void (CCObject::*SEL_MenuHandler)(CCObject*);
typedef void (CCObject::*SEL_EventHandler)(CCEvent*);
typedef int (CCObject::*SEL_Compare)(CCObject*);
#define schedule_selector(_SELECTOR) (SEL_SCHEDULE)(&_SELECTOR)
#define callfunc_selector(_SELECTOR) (SEL_CallFunc)(&_SELECTOR)
#define callfuncN_selector(_SELECTOR) (SEL_CallFuncN)(&_SELECTOR)
#define callfuncND_selector(_SELECTOR) (SEL_CallFuncND)(&_SELECTOR)
#define callfuncO_selector(_SELECTOR) (SEL_CallFuncO)(&_SELECTOR)
#define menu_selector(_SELECTOR) (SEL_MenuHandler)(&_SELECTOR)
#define event_selector(_SELECTOR) (SEL_EventHandler)(&_SELECTOR)
#define compare_selector(_SELECTOR) (SEL_Compare)(&_SELECTOR)
所以CCObject之外類,但在cocos2d名稱空間中,存在函數指針和幫助宏的聲明以使用它們。我正確地調用函數指針的這些聲明嗎?
我理解的typedef是一個關鍵字與類型關聯(見Typedef function pointer?),並且返回類型是必須是void和函數必須具有CCObject的一個強制性的說法*。但是我迷失於理解其適當的用法,範圍,以及C++如何通過另一個函數來傳遞函數。
問題1
我不是下面如何解釋聲明函數指針的範圍。在它們的聲明中,它們顯示函數指針被CCObject類限定。我應該如何理解?這是否意味着它被指定該功能屬於CCObject的成員函數?這對我來說很混亂,因爲它是在課堂外定義的,但是與CCObject有關。
typedef void (CCObject::*SEL_MenuHandler)(CCObject*);
問題2
在cocos2d的-X CCMenuItem類,它定義下面
// How does C++ treat the this? Is a function treated like an object here?
static CCMenuItem* create(CCObject *rec, SEL_MenuHandler selector);
CCMenuItem* CCMenuItem::create(CCObject *rec, SEL_MenuHandler selector)
{
CCMenuItem *pRet = new CCMenuItem();
pRet->initWithTarget(rec, selector);
pRet->autorelease();
return pRet;
}
bool CCMenuItem::initWithTarget(CCObject *rec, SEL_MenuHandler selector)
{
setAnchorPoint(ccp(0.5f, 0.5f));
m_pListener = rec;
m_pfnSelector = selector;
m_bEnabled = true;
m_bSelected = false;
return true;
}
// A snippet from CCMenuItem header
protected:
CCObject* m_pListener;
SEL_MenuHandler m_pfnSelector; // member variable which stores a pointer to a function?
int m_nScriptTapHandler;
};
靜態工廠方法因此,這是否typedef的意思是當我傳遞一個函數它,我正在用指針傳遞值?如果函數沒有被指針傳遞,C++如何處理這個問題。函數是否像對象一樣被拷貝構造函數對待?
我感謝任何幫助和建議。感謝
謝謝,這很有幫助 –