有趣的是,将函数名称用作函数指针等同于将address-of运算符应用于函数名称!
这是一个例子.
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;
}
Run Code Online (Sandbox Code Playgroud)
使用这个名称是我们在数组中已经知道的.但是你不能写出类似的东西
int a[2];
int * b = &a; // Error!
Run Code Online (Sandbox Code Playgroud)
这似乎与该语言的其他部分不一致.这个设计的基本原理是什么?
这个问题解释了这种行为的语义及其工作原理.但是我对这种语言设计的原因很感兴趣.
更有趣的是,当用作参数时,函数类型可以隐式转换为指向自身的指针,但在用作返回类型时不会转换为指向自身的指针!
例:
typedef bool FunctionType(int);
void g(FunctionType); // Implicitly converted to void g(FunctionType …Run Code Online (Sandbox Code Playgroud) 我想知道为什么这段代码的两个版本都没有错误:
#include <iostream>
bool check_number(int n) {
return n < 5;
}
int main() {
int number = 6;
// (1) prints "Hello World"
if (check_number)
// (2) prints "not hello world"
if (check_number(number))
{
std::cout << "Hello world!";
}
else
{
std::cout << "not hello world";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Hello world!尽管我没有将变量传递到if 语句中的number函数中,但条件 (1) 仍会打印。check_number
在情况(2)中,我得到了not hello world预期的结果。