How can I pass a member function where a free function is expected?

后端 未结 9 1769
误落风尘
误落风尘 2020-11-22 15:10

The question is the following: consider this piece of code:

#include 


class aClass
{
public:
    void aTest(int a, int b)
    {
        prin         


        
9条回答
  •  难免孤独
    2020-11-22 15:28

    A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1 would be

    void function1(void (aClass::*function)(int, int), aClass& a) {
        (a.*function)(1, 1);
    }
    

    and to call it:

    aClass a; // note: no parentheses; with parentheses it's a function declaration
    function1(&aClass::test, a);
    

提交回复
热议问题