如何用cout打印函数指针? [英] How to print function pointers with cout?

查看:459
本文介绍了如何用cout打印函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用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\n", pf);
    return 0;
}

我用g ++编译它,得到如下结果:

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


cout < pf为1

cout<< (void *)pf is 0x100000b0c

printf(%p,pf)is 0x100000b0c

cout << pf is 1
cout << (void *)pf is 0x100000b0c
printf("%p", pf) is 0x100000b0c

做cout做类型int(*)()?我被告知,函数指针被当作bool,是真的吗?
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 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.

这篇关于如何用cout打印函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆