【发布时间】:2012-08-28 02:50:12
【问题描述】:
有趣的是使用函数名作为函数指针相当于将地址运算符应用于函数名!
这是示例。
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).
【问题讨论】:
标签: c++ syntax function-pointers