且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于函数声明中的函数指针

更新时间:2022-12-23 15:12:58

当你写int fun2(int fun())时,参数int fun()转换进入int (*fun)(),它变成完全等同于这个:

When you write int fun2(int fun()), the parameter int fun() converts into int (*fun)(), it becomes exactly equivalent to this:

int fun2(int (*fun)());

当您将数组声明为函数参数时,会发生更熟悉的转换.例如,如果你有这个:

A more famiiar conversion happens in case of array when you declare it as function parameter. For example, if you've this:

int f(int a[100]);

即使在这里参数类型也转换成int*,变成这样:

Even here the parameter type converts into int*, and it becomes this:

int f(int *a);

函数类型和数组类型之所以分别转换为函数指针类型和指针类型,是因为标准不允许将函数和数组传递给函数,也不能你从一个函数返回函数和数组.在这两种情况下,它们都会衰减到它们的指针版本.

The reason why function type and array type converts into function pointer type, and pointer type, respectively, is because the Standard doesn't allow function and array to be passed to a function, neither can you return function and array from a function. In both cases, they decay into their pointer version.

C++03 标准在 §13.1/3 中说(在 C++11 中也是如此),

The C++03 Standard says in §13.1/3 (and it is same in C++11 also),

区别仅在于一个是函数类型而另一个是指向同一函数类型的指针的参数声明是等价的.也就是将函数类型调整为指向函数类型的指针(8.3.5).

Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5).

这里还有一个更有趣的讨论:

And a more interesting discussion is here: