C++ 函数指针的计算结果为 1

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。

M.M*_*M.M 6

没有operator<<which takestd::ostream和函数指针的重载。然而,有一个接受std::ostream和 a bool,并且存在从函数指针到 bool 的隐式转换。

因此,您的代码将函数指针转换为,如果它不是空指针,bool则定义为产生;true然后是outputs true1默认定义为输出。您可以std::cout<< std::boolalpha << fcptr;查看true输出。