2013-09-27 80 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的建议使用了虚拟函数。虽然谢谢! –