hac*_*eas 3 c++ pointers function-pointers function
我定义了一个指向函数的简单函数指针,当我尝试输出时,它的值为 1。幕后发生了什么?(我在mac上,用c++11 g++编译器编译)
#include <iostream>
int foo()
{
return 5;
}
int main(int argc, char const *argv[])
{
int (*fcptr)() = foo;
std::cout<< fcptr;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出为1。
没有operator<<
which takestd::ostream
和函数指针的重载。然而,有一个接受std::ostream
和 a bool
,并且存在从函数指针到 bool 的隐式转换。
因此,您的代码将函数指针转换为,如果它不是空指针,bool
则定义为产生;true
然后是outputs true
,1
默认定义为输出。您可以std::cout<< std::boolalpha << fcptr;
查看true
输出。