Using function pointers?
I'm not yet very familiar with these but maybe someone can shine light on this example.
Imagine I have class CFoo and it will have a function to add a handler and a function which is a function pointer.
So something like this:
class CFoo {
int *pointedFunc(int a, int b) = 0;
void setFunc(int *func(int a, int b))
{
pointedFunc = func;
}
};
Given the above context, I want to know the proper way o开发者_如何学JAVAf doing this. I don't think I have done it properly. Also, how would I go about calling pointedFunc?
Thanks
Right now you have a member function returning int *
, not a pointer to a function returning int
. A set of parenthesis would fix that.
int (*pointedFunc)(int a, int b);
void setFunc(int (*pfunc)(int a, int b))
{
pointedFunc = pfunc;
}
Also, member variables get initialized in the constructor ctor-initializer-list, like
CFoo::CFoo() : pointedFunc(0) {}
not like you did. Your = 0
was actually a pure-specifier (and it won't work unless the member function is virtual), when you fix the pointer-return-type vs pointer-to-function issue you'll find that the compiler also complains about your attempt to initialize it.
Using a typedef as Graeme suggests is the easiest and best way to keep track of function-pointer types.
In your example, pointedFunc
is a member function that returns an int *
. To make it a function pointer, you need parens around pointedFunc
, like:
int (*pointedFunc)( int a, int b );
A typedef might make it clearer:
class CFoo {
CFoo() : pointedFunc( NULL ) {}
typedef int (*funcType)(int, int);
funcType pointedFunc;
void setFunc( funcType f ) {
pointedFunc = f;
}
};
To call the function, you can use either pointedFunc( 1, 2 )
or (*pointedFunc)(1, 2)
. I tend to use the latter to make it clear that you are going through a function pointer, but either will work.
精彩评论