繁体   English   中英

将成员函数指针传递给父类

[英]Pass Member Function Pointers to parent class

我正在使用C ++编写Pacman游戏,但遇到了成员函数指针的问题。 我有两个班, pacmanghost ,都继承自Mouvement 在子类中,我需要将一个函数传递给Mouvement一个函数。 但是,我不能简单地拥有静态函数,因为我需要静态变量,这是行不通的。

我试过传递&this->movingUp抛出错误'无法创建一个非常量的指向成员函数的指针'

我已经尝试传递&<ghost or pacman>::movingUp ,它抛出错误“无法使用'void(:: )(int)' 类型的右值初始化'void( )(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);}
    }

};

为什么不在cMouvement创建虚函数,让checkIntersection调用该虚函数

你想要的是提供成员函数的签名,而不是常规函数。

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

请参阅在C ++中将成员函数作为参数传递

如果你真的需要提供ghost pacman功能,你需要重新考虑你的策略。 也许使用虚拟功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM