I'm asking some specific questions.
- How can I initialize them in a class?
- How can I pass a function as an argument?
- Do function pointers need to be declared and defined in the class?
For question number 2 here is what I mean:
void s(void) {
//...
}
void f(function) { // what should I put as type to pass a function as an argument
//...
}
f(s);
To define a function pointer, use the following syntax:
return_type (*ref_name) (type args, ...)
So, to define a function reference named "doSomething", which returns an int
and takes in an int
argument, you'd write this:
int (*doSomething)(int number);
You can then assign the reference to an actual function like this:
int someFunction(int argument) {
printf("%i", argument);
}
doSomething = &someFunction;
Once that's done, you can then invoke it directly:
doSomething(5); //prints 5
Because function pointers are essentially just pointers, you can indeed use them as instance variables in your classes.
When accepting function pointers as arguments, I prefer to use a typedef
instead of using the cluttered syntax in the function prototype:
typedef int (*FunctionAcceptingAndReturningInt)(int argument);
You can then use this newly defined type as the type of the argument for the function:
void invokeFunction(int func_argument, FunctionAcceptingAndReturningInt func) {
int result = func(func_argument);
printf("%i", result);
}
int timesFive(int arg) {
return arg * 5;
}
invokeFunction(10, ×Five); //prints 50
it is not the strict answer , but to include configurable/assignable code as a class member, I would mention using a class/struct with the operator() . For example:
struct mycode
{
int k;
mycode(int k_) : k(k_)
{
}
int operator()(int x)
{
return x*k;
}
};
class Foo
{
public : Foo(int k) : f(k) {}
public : mycode f;
};
You can do:
Foo code(5);
std::cout << code.f(2) << std::endl;
it will print '10' , it I wrote everything ok.
You have to declare f
in this way:
void f(void (*x)())
{
x(); // call the function that you pass as parameter (Ex. s()).
}
here is an excellent tutorial about function pointers and callbacks.
To answer 3rd question, you do not have to declare it in a class. But not to transgress encapsulation, I usually prefer member function pointers or functors which pointees are again members of classes. Examples above are C style function pointers except Luis G. Costantini R. You can take a look at this for member function pointers approach. C style function pointers are generally considered, for example, callback mechanisms where there is a C code which you receive asynchronous messages. In such cases, there are no options rather than declaring handler methods in global scope.
来源:https://stackoverflow.com/questions/4528808/how-do-function-pointers-work