首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数指针-2选项

函数指针-2选项
EN

Stack Overflow用户
提问于 2015-11-12 16:15:41
回答 1查看 134关注 0票数 8

我想知道这两个函数( funfun2 )之间有什么区别,我知道fun2是函数指针,但是fun又有什么区别呢?这是否相同,因为也有传递指针,即函数名?

代码语言:javascript
复制
#include <iostream>

void print()
{
  std::cout << "print()" << std::endl;
}

void fun(void cast())
{
  cast();
}

void fun2(void(*cast)())
{
  cast();
}

int main(){
  fun(print);
  fun2(print);
} 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-12 17:02:54

这是否相同,因为也有传递指针,即函数名?

是。这是从C继承来的,完全是为了方便。fun和fun2都接受一个类型为"void ()“的指针。

这种方便是允许存在的,因为当您使用括号调用函数时,不存在歧义。如果您有括号大小的参数列表,则必须是调用函数。

如果禁用编译器错误,以下代码也将工作:

代码语言:javascript
复制
fun4(int* hello) {
     hello(); // treat hello as a function pointer because of the ()
}

fun4(&print);

http://c-faq.com/~scs/cclass/int/sx10a.html

Why is using the function name as a function pointer equivalent to applying the address-of operator to the function name?

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33676126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档