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/12152167/

相关文章:

c++ - 使用 Visual Studio Compiler 分析内联 C++ 函数

c++ - 如何编译Detours Express 3.0?

c++ - 读取包含 16 位签名数据的文件

c++ - 将在类中声明的函数作为参数传递会导致编译错误

c++ - 当包含类头时,为什么我的数组在 main 中未定义?

c++ - 我可以在 .pro 文件中使用 Qt 安装路径变量吗?

perl - 如何引用 Perl 中的数组切片?

javascript 自执行函数 - 不同的语法

Javascript 对象 Prop

arrays - Fortran 中的函数指针数组