Member function pointers are different from normal function pointers. A normal function pointer looks like this:
void foo() {}
void (*Func)() = foo; // Function pointer.
And a member function pointer looks like this:
class MemberTest {
public:
void foo() {}
};
void (MemberTest::*Func)() = &MemberTest::foo; // Member function pointer. Notice the '&' operator here.
int main()
{
MemberTest test;
(test.*Func)(); // This is how to call member function pointers.
}
Accordingly, for your problem there, you need to define it as a member function pointer and not like a normal function pointer:
void foo(void (bar::*hndlr)());
And when calling the foo()
function, it must return the address of the member function:
void init()
{
foo(&bar::clbck);
}
But still, you can't call the function from foo()
like this, as it doesn't have the current instance of the bar
object. So we have to make another parameter which takes the pointer to the current object:
void foo(bar* pBar, void (bar::*hndlr)());
...
foo(this, &bar::clbck);
So now, when calling the member function from foo()
, you can do it like this:
(pBar->*hndlr)();
Note: Add a forward declaration on top of the function foo()
or else the compiler might complain saying that bar
is undefined.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…