How do function pointers work?

泄露秘密 提交于 2019-11-30 19:38:51

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, &timesFive); //prints 50
Javier Loureiro

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.

Luis G. Costantini R.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!