我想用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;
}
Run Code Online (Sandbox Code Playgroud)
我用g ++编译它并获得如下结果:
cout << pf是1
cout <<(void*)pf是0x100000b0c
printf("%p",pf)是0x100000b0c
那么cout对int(*)()类型做了什么?我被告知函数指针被视为bool,是真的吗?cout用type(void*)做什么?
提前致谢.
编辑:无论如何,我们可以通过将函数指针转换为(void*)并使用cout将其打印出来来观察函数指针的内容.但它对成员函数指针不起作用,编译器抱怨非法转换.我知道成员函数指针是一个比简单指针更复杂的结构,但是我们如何才能观察成员函数指针的内容呢?
我最近偶然发现了以下gcc 3.2.2编写ac程序的行为:
在if语句中,我忘记了函数的大括号,并写道:
if(myFunc)... 代替 if(myFunc())...
虽然我几乎每个警告都打开了,但这并没有产生错误.
它只是评估为true.为什么这首写法律代码?因为函数存在/有地址?有谁知道如何避免这样的错误,或者是否有一个我忽略的警告选项?这个问题在以后的gcc版本中是否能更好地解决?
这里是完整性的确切编译器调用:
msp430-gcc -g -Os -mmcu=msp430x1611 -Wall -W -Wfloat-equal -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wwrite-strings -Wsign-compare -Waggregate-return -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations
-Wredundant-decls -Wnested-externs -Wimplicit-function-declaration -Werror
Run Code Online (Sandbox Code Playgroud)
(因为我被迫使用gcc 3.2.3,所以没有-Wextra)