简体   繁体   中英

In C++, how do I declare a function pointer to a method in a class?

In C++, I'm trying to define a type suitable for a pointer to one of several member functions of my class cBar (all functions have the same interface, say accept an int and return void ).

For now, I'm making a global type tHandler suitable for a pointer to one of several global functions accepting an additional parameter me , holding a pointer to my class cBar , as follows:

typedef void(*tHandler)(class cBar *const me, int val);

void Handler0(class cBar *const me, int val);
void Handler1(class cBar *const me, int val);

class cBar {
    tHandler fCurrentHandler;
    /*..*/
public:
    inline void cBar::CurrentHandler(int val) {
        (*fCurrentHandler)(this,val);
        }
    inline cBar() {
        fCurrentHandler = Handler0;
        CurrentHandler(0);
        }
    inline ~cBar() {
        CurrentHandler(-1);
        }
    };

This is ugly; in particular Handler0 and Handler1 should be private methods of cBar , and tHandler should be a private type.

Any clue? TIA.

A pointer to a member can be declared like

typedef void(Trustee::*tHandler)(int);

Here's how to use it (adaptation of your own code):

class Trustee {
    typedef void(Trustee::*handler_t)(int);
    handler_t pfCurrentHandler;
    void handlerOne(int i) { cout << "HandlerOne: " << i << endl; } 
    void handlerTwo(int i) { cout << "HandlerTwo: " << i << endl; } 
public:
    void CurrentHandler(int val) {
        (this->*pfCurrentHandler)(val);
    }
    Trustee() : pfCurrentHandler(&Trustee::handlerOne) {
        CurrentHandler(0);
    }
    ~Trustee() {
        CurrentHandler(-1);
    }
};

Pay particular attention to the operator ->* , which is not something you see every day.

See it in action .

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