【发布时间】:2011-01-05 02:25:37
【问题描述】:
我想使用 cout 打印出一个函数指针,发现它不起作用。 但是在我将函数指针转换为(void *)之后它起作用了,printf也是如此,带有%p,例如
#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\n", pf);
return 0;
}
我用g++编译得到如下结果:
cout cout printf("%p", pf) 为 0x100000b0c
那么 cout 对 int (*)() 类型做了什么?有人告诉我函数指针被视为布尔值,是真的吗? cout 对 type (void *) 做了什么?
提前致谢。
编辑:无论如何,我们可以通过将函数指针转换为 (void *) 并使用 cout 打印出来来观察函数指针的内容。 但它不适用于成员函数指针,编译器抱怨非法转换。我知道成员函数指针不是简单的指针,而是一个比较复杂的结构,但是如何观察成员函数指针的内容呢?
【问题讨论】:
标签: c++