简体   繁体   中英

Pass Member Function Pointers to parent class

I'm working on a Pacman game in C++, but have run into a problem with member function pointers. I have 2 classes, pacman and ghost , that both inherit from Mouvement . In the subclasses, I need to pass a function to a function in Mouvement . However, I can't simply have static functions as then I would need static variables, which would not work.

I have tried passing &this->movingUp which throws the error 'Cannot create a non-constant pointer to member function'

I have tried passing &<ghost or pacman>::movingUp which throws the error "Cannot initialize a parameter of type 'void ( )(int)' with an rvalue of type 'void (:: )(int)' "

Here's what's relevent: (I cut out most of it, so that you only see what's necessary for this problem)

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

}

And then class pacman and ghost , which are very similar at this point.

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调用该虚函数

What you want is to supply the signature of a member function, instead of a regular function.

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

See Passing a member function as an argument in C++

If you really need to supply functions from ghost and pacman you need to rethink your strategy. Maybe use virtual functions instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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