函数和作为参数的函数指针之间的区别
这是一个相当简单的问题,让我有点好奇。考虑以下代码片段:
#include <iostream>
int three()
{
return 3;
}
void foo(int func(void))
{
std::cout << func() << std::endl;
}
void bar(int (*func)(void))
{
std::cout << func() << std::endl;
}
int main()
{
foo(three);
bar(three);
return 0;
}
// output:
// 3
// 3
如您所见,我们有两个函数将另一个函数作为唯一参数。然而,它们的函数原型有所不同。主要有 void foo(int func(void))
和 void bar(int (*func)(void))
。乍一看,foo
似乎正在获取函数本身,而 bar
正在获取指向函数的指针。
然而,它们都产生完全相同的结果,并且具有完全相同的主体,并且以完全相同的方式调用。
我的问题是, foo
和 bar
之间是否存在真正隐藏的区别?这只是 C++ 中的可选语法吗?在 C++ 中,这两种情况之一是否被认为是“糟糕的风格”?
如果我的编译器是一个影响因素,那么我使用的是 Visual Studio 2010。
This is a rather simple question that is making me a bit curious. Consider the following code snippet:
#include <iostream>
int three()
{
return 3;
}
void foo(int func(void))
{
std::cout << func() << std::endl;
}
void bar(int (*func)(void))
{
std::cout << func() << std::endl;
}
int main()
{
foo(three);
bar(three);
return 0;
}
// output:
// 3
// 3
As you can see, we have two functions that take another function as their only argument. However, the function prototypes for them differ. Mainly, we have void foo(int func(void))
and void bar(int (*func)(void))
. At first glance, it looks like foo
is taking the function itself, and bar
is taking a pointer to a function.
However, they both produce the exact same results, and have the exact same body, and are called in exactly the same manner.
My question is, is there an actually hidden difference between foo
and bar
? Is this simply an optional syntax in C++? Is one of the two cases considered "bad style" in C++?
If my compiler is a contributing factor, I'm using Visual Studio 2010.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有区别:
foo
和bar
的类型相同:int(int(*)())
。不存在函数类型参数这样的东西:当参数以函数类型语法(如
int func(void)
)出现时,它会转换为相应的函数指针类型(就像int (*func)(void)
)。该转换类似于如何将使用数组语法声明的参数(例如
int a[]
)转换为相应的指针类型(int* a
)。There is no difference: the types of
foo
andbar
are the same:int(int(*)())
.There is no such thing as a function-type parameter: when a parameter appears with the function type syntax (like
int func(void)
), it is transformed into the corresponding pointer-to-function type (likeint (*func)(void)
).The transformation is similar to how a parameter declared with array syntax (e.g.
int a[]
) is transformed into the corresponding pointer type (int* a
).