(Simple?) pointer to non-static member function question
See the code below - I want to know how to, or if it is even possible to, write the body of A::DoThisOrThat()
class A
{
void DoThis( void ) { // any function body you like... }
void DoThat( void ) { // any function body you like... }
void DoThisOrThat( const bool doThis );开发者_开发问答
};
void A::DoThisOrThat( const bool doThis )
{
void (*pMemberFunction)( void );
pMemberFunction = doThis? &A::DoThis : &A::DoThat;
(*pMemberFunction)(); // member function invoked controlled by parameter
}
All three lines of this function may need rewriting to correctly scope the member function. As written, I get a calling convention conflict on the second line where I assign pMemberFunction. I cannot lay my hands on a simple example clarifying this - all the examples easily found declare a member variable to hold the member function pointer. Can I not just create a local variable to do the same?
I might be missing something, but isn't it much easier and simpler to do this?
void A::DoThisOrThat(bool doThis)
{
if(doThis) { DoThis(); }
else { DoThat(); }
}
Assuming you really want to go the function pointer route, realize that pointer to member functions are completely different beasts from pointers to non-member functions. One of the ways they are different is that you need to provide an object for the function to invoke upon. The syntax is as follows:
void A::DoThisOrThat(bool doThis)
{
void (A::*pMemberFunction)();
pMemberFunction = doThis ? &A::DoThis : &A::DoThat;
(this->*pMemberFunction)();
}
Note that when declaring a pointer to member function, you have to also specify the class (note the A::*
) and the object (note the this->*
). Also remember that when forming pointers to members you have to fully qualify the function name, even within the class, and use the ampersand (e.g. &A::DoThis
, which you've correctly done).
Member functions aren't free functions, and pointers-to-member-function (PTMF) are not function pointers! They're entirely incompatible. (Typically they are much bigger.) Much more importantly, you can only call a member function if you have both a PTMF and an instance pointer.
So, you have to say:
void A::DoThisOrThat( const bool doThis )
{
void (A::*pMemberFunction)( void );
pMemberFunction = doThis? &A::DoThis : &A::DoThat;
(this->*pMemberFunction)();
}
(Not that there's any reason for this amount of indirection if all you want is to branch on one local conditional.)
Replace these:
void (*pMemberFunction)( void );
(*pMemberFunction)(); // member function invoked controlled by parameter
with:
void (A::*pMemberFunction)( void );
(*this->pMemberFunction)(); // member function invoked controlled by parameter
精彩评论