问题描述
我想使用 cout 打印出一个函数指针,发现它不起作用.但是在我将函数指针转换为(void *)后它起作用了,printf也是如此,带有%p,例如
I want to print out a function pointer using cout, and found it did not work. But it worked after I converting the function pointer to (void *), so does printf with %p, such as
#include <iostream>
using namespace std;
int foo() {return 0;}
int main()
{
int (*pf)();
pf = foo;
cout << "cout << pf is " << pf << endl;
cout << "cout << (void *)pf is " << (void *)pf << endl;
printf("printf("%%p", pf) is %p
", pf);
return 0;
}
我用g++编译得到如下结果:
I compiled it with g++ and got results like this:
cout <<pf 为 1
cout <<(void *)pf 为 0x100000b0c
printf("%p", pf) 为 0x100000b0c
cout << pf is 1
cout << (void *)pf is 0x100000b0c
printf("%p", pf) is 0x100000b0c
那么 cout 对 int (*)() 类型做了什么?有人告诉我函数指针被视为布尔值,是真的吗?cout 对 type (void *) 做了什么?
So what does cout do with type int (*)()? I was told that the function pointer is treated as bool, is it true? And what does cout do with type (void *)?
提前致谢.
无论如何,我们可以通过将函数指针转换为 (void *) 并使用 cout 打印出来来观察函数指针的内容.但它不适用于成员函数指针,编译器抱怨非法转换.我知道成员函数指针不是简单的指针,而是一个比较复杂的结构,但是如何观察成员函数指针的内容呢?
Anyhow, we can observe the content of a function pointer by converting it into (void *) and print it out using cout. But it does not work for member function pointers and the compiler complains about the illegal conversion. I know that member function pointers is rather a complicated structure other than simple pointers, but how can we observe the content of a member function pointers?
推荐答案
其实有一个重载的<<看起来像这样的运算符:
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 there are 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++ 标准规定:
4.12 布尔转换
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.
这篇关于如何用 cout 打印函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!