如何函数指针的工作? [英] How do function pointers work?

查看:143
本文介绍了如何函数指针的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要问一些具体的问题。


  1. 如何初始化它们中的一类?

  2. 如何传递一个函数作为参数?

  3. 请函数指针需要申报,并在类中定义?

有关问题号码2这里是我的意思是:

 无效S(无效){
   // ...
}无效F(功能){//我应该把类型为传递函数作为参数
   // ...
}F(S);


解决方案

要定义一个函数指针,请使用以下语法:

  return_type(* ref_name)(类型ARGS,...)

因此​​,要定义一个名为DoSomething的函数引用,它返回一个 INT ,并采取在 INT 参数,你会这样写:

  INT(* DoSomething的)(INT号);

然后,您可以参考分配到这样一个实际的功能:

  INT someFunction(int参数){
   的printf(%i上的说法);
}DoSomething的=安培; someFunction;

一旦这样做了,你可以然后直接调用它:

  DoSomething的(5); //输出5

由于函数指针基本上只是指针,你的确可以在你的类使用它们作为实例变量。

在接受函数指针作为参数,我preFER使用的的typedef 而不是在函数原型使用混乱的语法:

 的typedef INT(* FunctionAcceptingAndReturningInt)(int参数);

您可以使用这个新定义的类型作为函数的参数的类型:

 无效invokeFunction(INT func_argument,FunctionAcceptingAndReturningInt FUNC){
   INT结果= FUNC(func_argument);
   的printf(%i的,结果);
}INT timesFive(INT ARG){
   返回ARG * 5;
}
invokeFunction(10,&安培; timesFive); //输出50

I'm asking some specific questions.

  1. How can I initialize them in a class?
  2. How can I pass a function as an argument?
  3. 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, &timesFive); //prints 50

这篇关于如何函数指针的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆