#include<stdio.h>
#include<stdlib.h>
int fun1()
{
printf("I am fun1.");
return 0;
}
int fun2(int fun())
{
fun();
return 0;
}
int main()
{
fun2(fun1);
return 0;
}
上面的程序可以运行了.就我而言,我能理解int fun2(int (*fun)()),但我不知道int fun2(int fun())作品.谢谢.
The above program can run. As far as I am concerned, I can understand int fun2(int (*fun)()), but I do not know how int fun2(int fun()) works. Thank you.
当你写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:
这篇关于关于函数声明中的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)