您的位置:首页 > 其它

(ZT) cout打印不了函数地址

2015-12-12 12:08 393 查看
/// cout 打印不了函数指针

/// http://stackoverflow.com/questions/2064692/how-to-print-function-pointers-with-cout

Q

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
[code]#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;
}


I compiled it with g++ and got results like this:

cout << pf is 1

cout << (void *)pf is 0x100000b0c

printf("%p", pf) is 0x100000b0c

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 *)?

Thanks in advance.

EDIT: 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?

A

There actually is an overload of the << operator that looks something like:
[code]ostream & operator <<( ostream &, const void * );


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.

Edit: The C++ Standard specifies:

4.12 Boolean conversions

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: