c++ - 函数指针 - 2 个选项

标签 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);
} 

最佳答案

Is that the same because there is also passing by pointer which is function name ?

是的。这是从C继承而来的,纯粹是为了方便。 fun 和 fun2 都接收一个类型为“void ()”的指针。

这种便利是允许存在的,因为当您调用带括号的函数时,没有歧义。如果您有带括号的参数列表,您必须调用一个函数。

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

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?

关于c++ - 函数指针 - 2 个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33676126/

相关文章:

c++ - 如何使用 C++ lambda 将成员函数指针转换为普通函数指针以用作回调

指向函数的 C typedef [c 语法]

c++ - 涉及非常快速地跨网络发送数据的 C/C++ 技术

c++ - 将 0 到 x 的整数范围分配给容器的最快方法

c++ - 推导函数指针返回类型

c - 函数指针签名不匹配,执行程序时仍然没有遇到任何问题

c++ - 检索对象的函数运算符的参数类型

C++ 多态静态可变子函数指针

c++ - C++ 中的 move 语义是否缺少 C 所缺少的东西?

c++ - 如何限制 "using namespace ..."的范围? C++