我正在使用C++的Pacman游戏,但遇到了成员函数指针的问题。我有2个类,pacman
和ghost
,这两个类都从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
}
然后是类pacman
和ghost
,在这一点上非常相似。
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);}
}
};
这很好,谢谢。 –