c++ - 为什么将函数名用作函数指针等同于将寻址运算符应用于函数名?

标签 c++ syntax function-pointers

有趣的是,将函数名用作函数指针等同于将寻址运算符应用于函数名!

这是例子。

typedef bool (*FunType)(int);
bool f(int);
int main() {
  FunType a = f;
  FunType b = &a; // Sure, here's an error.
  FunType c = &f; // This is not an error, though. 
                  // It's equivalent to the statement without "&".
                  // So we have c equals a.
  return 0;
}

使用名称是我们在数组中已经知道的。但是你不能写类似

的东西
int a[2];
int * b = &a; // Error!

这似乎与语言的其他部分不一致。这样设计的原理是什么?

This question explains the semantics of such behavior and why it works.但我对为什么要这样设计语言很感兴趣。

更有趣的是函数类型在用作参数时可以隐式转换为指向自身的指针,但在用作返回类型时不会转换为指向自身的指针!

示例:

typedef bool FunctionType(int);
void g(FunctionType); // Implicitly converted to void g(FunctionType *).
FunctionType h(); // Error!
FunctionType * j(); // Return a function pointer to a function 
                    // that has the type of bool(int).

最佳答案

由于您特别询问此行为的基本原理,这是我能找到的最接近的东西(来自 ANSI C90 基本原理文档 - http://www.lysator.liu.se/c/rat/c3.html#3-3-2-2):

3.3.2.2 Function calls

Pointers to functions may be used either as (*pf)() or as pf(). The latter construct, not sanctioned in the Base Document, appears in some present versions of C, is unambiguous, invalidates no old code, and can be an important shorthand. The shorthand is useful for packages that present only one external name, which designates a structure full of pointers to object s and functions : member functions can be called as graphics.open(file) instead of (*graphics.open)(file). The treatment of function designators can lead to some curious , but valid , syntactic forms . Given the declarations :

int f ( ) , ( *pf ) ( ) ; 

then all of the following expressions are valid function calls :

( &f)(); f(); (*f)(); (**f)(); (***f)();
pf(); (*pf)(); (**pf)(); (***pf)();

The first expression on each line was discussed in the previous paragraph . The second is conventional usage . All subsequent expressions take advantage of the implicit conversion of a function designator to a pointer value , in nearly all expression contexts . The Committee saw no real harm in allowing these forms ; outlawing forms like (*f)(), while still permitting *a (for int a[]), simply seemed more trouble than it was worth .

基本上,添加了函数指示符和函数指针之间的等价性,使函数指针的使用更加方便。

关于c++ - 为什么将函数名用作函数指针等同于将寻址运算符应用于函数名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27766896/

相关文章:

c++ - cocos2d-x中使用CCBReader报错

c++ - wdk ddk 编译器问题与 OutputDebugString

bash - 令人困惑的标记语法

JavaScript 语法问题 : [{ }] hierarchy

c# - 如何在 C# 中实现 C++ 风格的函数指针?,不使用委托(delegate)

c++ - 排序给出最后位置元素的错误输出

c++ - 动态构造函数

bash - 将多个命令的输出重定向到一个文件

c - 不确定如何将 C 中函数的参数转换为 void *

c - 如何将 char 数组转换为 C 中的函数指针?