如何函数指针的工作?

编程入门 行业动态 更新时间:2024-10-27 16:39:29
本文介绍了如何函数指针的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要问一些具体的问题。

  • 如何初始化它们中的一类?
  • 如何传递一个函数作为参数?
  • 请函数指针需要申报,并在类中定义?
  • 有关问题号码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.

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

    更多推荐

    如何函数指针的工作?

    本文发布于:2023-07-29 08:35:49,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1239128.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:指针   函数   工作

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!