且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用cout打印函数指针?

更新时间:2023-12-02 22:40:04

实际上有<<操作符:

There actually is an overload of the << operator that looks something like:

ostream & operator <<( ostream &, const void * );

这是您期望的输出。对于函数指针,可能没有这样的标准库重载,因为它们是无限数量的类型的。所以指针被转换为另一个类型,在这种情况下似乎是一个bool - 我不能忘记这个规则。

which does what you expect - outputs in hex. There can be no such standard library overload for function pointers, because are are an infinite number of types of them. So the pointer gets converted to another type, which in this case seems to be a bool - I can't offhand remember the rules for this.

编辑: C ++标准指定:

The C++ Standard specifies:


4.12布尔转换

4.12 Boolean conversions

1算术的右值,
枚举,指针或指向
成员类型的指针可以转换为bool类型的
值。

1 An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool.

这是为函数指针指定的唯一转换。

This is the only conversion specified for function pointers.