有趣的是,将函数名用作函数指针等同于将寻址运算符应用于函数名!
这是例子。
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 aspf()
. 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 asgraphics.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
(forint a[])
, simply seemed more trouble than it was worth .
基本上,添加了函数指示符和函数指针之间的等价性,使函数指针的使用更加方便。
关于c++ - 为什么将函数名用作函数指针等同于将寻址运算符应用于函数名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319977/