【问题标题】:Function Pointer - 2 options函数指针 - 2 个选项
【发布时间】:2015-11-12 16:15:41
【问题描述】:

我想知道这两个函数有什么区别(fun 和 fun2)我知道 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);
} 

【问题讨论】:

  • 函数参数声明调整为指向函数类型。它们都是等价的。

标签: c++ function-pointers


【解决方案1】:

是不是也一样,因为也有函数名指针传递?

是的。这是从 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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多