功能指针 - 2个选项

Han*_*123 8 c++ function-pointers

我想知道这两个函数之间有什么区别(funfun2)我知道这fun2是函数指针但是有什么用fun?这是相同的,因为还有通过指针的功能名称吗?

#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);
} 
Run Code Online (Sandbox Code Playgroud)

Tob*_*Liu 5

这是相同的,因为还有通过指针的功能名称吗?

是.这是继承自C.它只是为了方便.fun和fun2都带有"void()"类型的指针.

允许存在这种便利性,因为当您使用括号调用函数时,没有AMBIGUITY.你必须,如果你有一个括号参数列表来调用一个函数.

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

fun4(int* hello) {
     hello(); // treat hello as a function pointer because of the ()
}

fun4(&print);
Run Code Online (Sandbox Code Playgroud)

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

为什么使用函数名作为函数指针等效于将address-of运算符应用于函数名?