Use member function as function pointer

时间:2015-10-06 09:01:00

标签: c++ member-function-pointers

I've never used function pointers before and I'm having some trouble getting my code to work. This is what I have

TestClass.h:

class TestClass
{
    public:
        void function1();
        void function2();

        void function3(void (*funcPtr)(void))
        void function4();
};

TestClass.cpp

void TestClass::function1()
{
    //CODE
}

void TestClass::function2()
{
    //CODE
}

void TestClass::function3(void (*funcPtr)(void))
{
    //CODE
    funcPtr();
    //CODE
}

void TestClass::function4()
{
    function3(function1);
    function3(function2);
}

This give me the error

"nonstandard form for taking the address of a member function

I tried to add TestClass:: infront of the *funcPtr but that gives me even more errors

2 个答案:

答案 0 :(得分:7)

With member function pointer, it should be something like:

void TestClass::function3(void (TestClass::*funcPtr)())
{
    //CODE
    (this->*funcPtr)();
    //CODE
}

void TestClass::function4();
{
    function3(&TestClass::function1);
    function3(&TestClass::function2);
}

With function pointer

class TestClass
{
    public:
        static void function1(); // static added
        static void function2(); // static added

        void function3(void (*funcPtr)(void))
        void function4();
};

void TestClass::function3(void (*funcPtr)())
{
    //CODE
    funcPtr();
    //CODE
}

void TestClass::function4();
{
    function3(&TestClass::function1);
    function3(&TestClass::function2);
}

答案 1 :(得分:1)

我建议你使用std :: bind和std :: function,这样可以提供更好的可读性和更多的检查

http://en.cppreference.com/w/cpp/utility/functional/bind

#include <functional>

void TestClass::function3( std::function<void (void)> funcPtr )
{
    //CODE
    funcPtr();
    //CODE
}

void TestClass::function4()
{
    function3( std::bind(&TestClass::function1, this) );
    function3( std::bind(&TestClass::function2, this) );
}