C++ 函数指针的计算结果为 1
c++ function pointer evaluates to 1
我定义了一个指向函数的简单函数指针,当我尝试输出它时,它的计算结果为 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;
}
输出为 1。
没有 operator<<
的重载需要 std::ostream
和一个函数指针。但是,有一个接受 std::ostream
和一个 bool
,并且存在从函数指针到 bool.
的隐式转换
因此您的代码将函数指针转换为 bool
,如果它不是空指针,则定义为产生 true
;然后输出 true
,默认定义为输出 1
。您可以执行 std::cout<< std::boolalpha << fcptr;
以查看 true
输出。
我定义了一个指向函数的简单函数指针,当我尝试输出它时,它的计算结果为 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;
}
输出为 1。
没有 operator<<
的重载需要 std::ostream
和一个函数指针。但是,有一个接受 std::ostream
和一个 bool
,并且存在从函数指针到 bool.
因此您的代码将函数指针转换为 bool
,如果它不是空指针,则定义为产生 true
;然后输出 true
,默认定义为输出 1
。您可以执行 std::cout<< std::boolalpha << fcptr;
以查看 true
输出。