C++ Typedef 函数指针?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4295432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:03:36  来源:igfitidea点击:

Typedef function pointer?

c++cpointerstypedef

提问by Hyman Harvin

I'm learning how to dynamically load DLL's but what I don't understand is this line

我正在学习如何动态加载 DLL,但我不明白的是这一行

typedef void (*FunctionFunc)();

I have a few questions. If someone is able to answer them I would be grateful.

我有几个问题。如果有人能够回答他们,我将不胜感激。

  1. Why is typedefused?
  2. The syntax looks odd; after voidshould there not be a function name or something? It looks like an anonymous function.
  3. Is a function pointer created to store the memory address of a function?
  1. 为什么typedef使用?
  2. 语法看起来很奇怪;之后void不应该有函数名之类的吗?它看起来像一个匿名函数。
  3. 是否创建了函数指针来存储函数的内存地址?

So I'm confused at the moment; can you clarify things for me?

所以我现在很困惑;你能帮我澄清一下吗?

回答by e2-e4

typedefis a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance

typedef是一种将名称与类型相关联的语言结构。
例如,您可以像使用原始类型一样使用它

  typedef int myinteger;
  typedef char *mystring;
  typedef void (*myfunc)();

using them like

像使用它们一样

  myinteger i;   // is equivalent to    int i;
  mystring s;    // is the same as      char *s;
  myfunc f;      // compile equally as  void (*f)();

As you can see, you could just replace the typedefedname with its definition given above.

如您所见,您可以将typedefed名称替换为上面给出的定义。

The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedefcan improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.

难点在于 C 和 C++ 中函数指针的语法和可读性,并且typedef可以提高此类声明的可读性。但是,语法是合适的,因为函数——与其他更简单的类型不同——可能有返回值和参数,因此有时需要冗长而复杂的函数指针声明。

The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.

对于指向函数数组的指针以及其他一些更间接的风格,可读性可能开始变得非常棘手。

To answer your three questions

回答你的三个问题

  • Why is typedef used?To ease the reading of the code - especially for pointers to functions, or structure names.

  • The syntax looks odd (in the pointer to function declaration)That syntax is not obvious to read, at least when beginning. Using a typedefdeclaration instead eases the reading

  • Is a function pointer created to store the memory address of a function?Yes, a function pointer stores the address of a function. This has nothing to do with the typedefconstruct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.

  • 为什么要使用 typedef?简化代码的阅读 - 特别是对于函数或结构名称的指针。

  • 语法看起来很奇怪(在指向函数声明的指针中)该语法不易于阅读,至少在开始时是这样。使用typedef声明可以简化阅读

  • 是否创建了函数指针来存储函数的内存地址?是的,函数指针存储函数的地址。这与typedef仅简化程序的写入/读取的构造无关;编译器只是在编译实际代码之前扩展 typedef 定义。

Example:

例子:

typedef int (*t_somefunc)(int,int);

int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

回答by Jacob Relkin

  1. typedefis used to alias types; in this case you're aliasing FunctionFuncto void(*)().

  2. Indeed the syntax does look odd, have a look at this:

    typedef   void      (*FunctionFunc)  ( );
    //         ^                ^         ^
    //     return type      type name  arguments
    
  3. No, this simply tells the compiler that the FunctionFunctype will be a function pointer, it doesn't defineone, like this:

    FunctionFunc x;
    void doSomething() { printf("Hello there\n"); }
    x = &doSomething;
    
    x(); //prints "Hello there"
    
  1. typedef用于别名类型;在这种情况下,您将别名FunctionFuncvoid(*)().

  2. 确实语法看起来很奇怪,看看这个:

    typedef   void      (*FunctionFunc)  ( );
    //         ^                ^         ^
    //     return type      type name  arguments
    
  3. 不,这只是告诉编译器该FunctionFunc类型将是一个函数指针,它没有定义一个,如下所示:

    FunctionFunc x;
    void doSomething() { printf("Hello there\n"); }
    x = &doSomething;
    
    x(); //prints "Hello there"
    

回答by Cheers and hth. - Alf

Without the typedefword, in C++ the declaration would declare a variable FunctionFuncof type pointer to function of no arguments, returning void.

如果没有这个typedef词,在 C++ 中,声明将声明一个FunctionFunc指向无参数函数的指针类型的变量,返回void.

With the typedefit instead defines FunctionFuncas a name for that type.

typedef相反,它定义FunctionFunc为该类型的名称。

回答by Halil Kaskavalci

If you can use C++11 you may want to use std::functionand usingkeyword.

如果您可以使用 C++11,您可能需要使用std::functionandusing关键字。

using FunctionFunc = std::function<void(int arg1, std::string arg2)>;

回答by alinsoar

For general case of syntax you can look at annex A of the ANSI C standard.

对于语法的一般的情况下,你可以看看ANSI C标准的附录A中

In the Backus-Naur form from there, you can see that typedefhas the type storage-class-specifier.

在那里的 Backus-Naur 形式中,您可以看到typedef具有类型storage-class-specifier.

In the type declaration-specifiersyou can see that you can mix many specifier types, the order of which does not matter.

在类型中,declaration-specifiers您可以看到可以混合多种说明符类型,其顺序无关紧要。

For example, it is correct to say,

例如,正确的说法是,

long typedef long a;

to define the type aas an alias for long long. So , to understand the typedef on the exhaustive use you need to consult some backus-naur form that defines the syntax (there are many correct grammars for ANSI C, not only that of ISO).

将类型定义a为 的别名long long。因此,要了解详尽使用的 typedef,您需要查阅一些定义语法的 backus-naur 形式(ANSI C 有许多正确的语法,而不仅仅是 ISO 的语法)。

When you use typedef to define an alias for a function type you need to put the alias in the same place where you put the identifier of the function. In your case you define the type FunctionFuncas an alias for a pointer to function whose type checking is disabled at call and returning nothing.

当您使用 typedef 为函数类型定义别名时,您需要将别名放在放置函数标识符的同一位置。在您的情况下,您将类型定义FunctionFunc为指向函数的指针的别名,该函数的类型检查在调用时被禁用并且不返回任何内容。

回答by Amjad

#include <stdio.h>
#include <math.h>

/*
To define a new type name with typedef, follow these steps:
1. Write the statement as if a variable of the desired type were being declared.
2. Where the name of the declared variable would normally appear, substitute the new type name.
3. In front of everything, place the keyword typedef.
*/

// typedef a primitive data type
typedef double distance;

// typedef struct 
typedef struct{
    int x;
    int y;
} point;

//typedef an array 
typedef point points[100]; 

points ps = {0}; // ps is an array of 100 point 

// typedef a function
typedef distance (*distanceFun_p)(point,point) ; // TYPE_DEF distanceFun_p TO BE int (*distanceFun_p)(point,point)

// prototype a function     
distance findDistance(point, point);

int main(int argc, char const *argv[])
{
    // delcare a function pointer 
    distanceFun_p func_p;

    // initialize the function pointer with a function address
    func_p = findDistance;

    // initialize two point variables 
    point p1 = {0,0} , p2 = {1,1};

    // call the function through the pointer
    distance d = func_p(p1,p2);

    printf("the distance is %f\n", d );

    return 0;
}

distance findDistance(point p1, point p2)
{
distance xdiff =  p1.x - p2.x;
distance ydiff =  p1.y - p2.y;

return sqrt( (xdiff * xdiff) + (ydiff * ydiff) );
}