The syntax looks odd (in the pointer to function declaration) 至少在开始时,这种语法并不明显 . 使用 typedef 声明可以简化阅读
Is a function pointer created to store the memory address of a function? 是的,函数指针存储函数的地址 . 这与 typedef 构造无关,它只能简化程序的写入/读取;编译器只是在编译实际代码之前扩展typedef定义 .
例:
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
using FunctionFunc = std::function<void(int arg1, std::string arg2)>;
8
#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) );
}
5 回答
typedef
是一种将名称与类型相关联的语言结构 .例如,您可以像使用原始类型一样使用它
使用它们就像
如您所见,您可以使用上面给出的定义替换typedefed名称 .
困难在于指向函数语法和C和C中的可读性,
typedef
可以提高此类声明的可读性 . 但是,语法是合适的,因为函数 - 与其他更简单的类型不同 - 可能具有返回值和参数,因此有时指向函数的冗长和复杂的声明 .对函数数组的指针以及其他一些更间接的风格,可读性可能开始变得非常棘手 .
回答你的三个问题
Why is typedef used? 简化代码的读取 - 尤其是指向函数或结构名称的指针 .
The syntax looks odd (in the pointer to function declaration) 至少在开始时,这种语法并不明显 . 使用
typedef
声明可以简化阅读Is a function pointer created to store the memory address of a function? 是的,函数指针存储函数的地址 . 这与
typedef
构造无关,它只能简化程序的写入/读取;编译器只是在编译实际代码之前扩展typedef定义 .例:
typedef
用于别名类型;在这种情况下,您将FunctionFunc
别名为void(*)()
.确实语法看起来很奇怪,看看这个:
FunctionFunc
类型是一个函数指针,它没有定义一个,如下所示:如果没有
typedef
单词,在C语句中,声明将声明一个变量FunctionFunc
,其类型指针指向无参数的函数,返回void
.使用
typedef
,它将FunctionFunc
定义为该类型的名称 .如果您可以使用C 11,则可能需要使用
std::function
和using
关键字 .