2013-09-27 83 views
0

我正在使用C++的Pacman遊戲,但遇到了成員函數指針的問題。我有2個類,pacmanghost,這兩個類都從Mouvement繼承。在子類中,我需要將函數傳遞給Mouvement中的函數。但是,我不能簡單地擁有靜態函數,因爲那樣我就需要靜態變量,這是行不通的。通過成員函數指向父類

我試圖傳遞&this->movingUp其中引發錯誤「不能創建一個非恆定的成員函數指針」

我試圖傳遞&<ghost or pacman>::movingUp它引發錯誤「不能初始化類型的參數「無效() (INT)」類型的右值‘無效(::)(INT)’「

這裏是什麼培訓相關:(我切出大部分,這樣你只能看到這個問題有什麼必要)

class cMouvement { 
protected: 

    int curDirection = -3; // Variables that are used in the 'movingUp, etc' functions. 
    int newDirection = -3; // And therefore can't be static 


public: 

void checkIntersection(void (*function)(int), bool shouldDebug){ 

    // Whole bunch of 'If's that call the passed function with different arguments 

} 

然後是類pacmanghost,在這一點上非常相似。

class pacman : public cMouvement { 

    void movingUp(int type){ 
     // Blah blah blah 
    } 

    // movingDown, movingLeft, movingRight... (Removed for the reader's sake) 



public: 
    /*Constructor function*/ 

    void move(bool shouldDebug){ 
     if (curDirection == 0)  {checkIntersection(&movingUp, false);} 
     else if (curDirection == 1)  {checkIntersection(&movingRight, false);} 
     else if (curDirection == 2)  {checkIntersection(&movingDown, false);} 
     else if (curDirection == 3)  {checkIntersection(&movingLeft, false);} 
    } 

}; 

回答

1

你爲什麼不以cMouvement創建一個虛擬功能,讓checkIntersection調用而不是常規的函數,虛函數

+0

這很好,謝謝。 –

1

你需要的是提供一個成員函數的簽名。

void checkIntersection(void (ghost::*)(int), bool shouldDebug){ 

Passing a member function as an argument in C++

如果你真的需要從ghostpacman你需要重新考慮自己的戰略提供的功能。也許使用虛擬功能。

+0

是的,我按照John Smith的建議使用了虛擬函數。雖然謝謝! –