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

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

问题描述

我想用 cout 打印出一个函数指针,发现它不起作用.但是在我将函数指针转换为 (void *) 之后它起作用了,带有 %p 的 printf 也是如此,例如

#include 使用命名空间标准;int foo() {返回 0;}int main(){int (*pf)();pf = foo;cout<<cout << pf 是" <<pf<<结束;cout<<"cout << (void *)pf 是" <<(void *)pf <<结束;printf("printf("%%p", pf) 是 %p
", pf);返回0;}

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

<块引用>

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

那么 cout 对 int (*)() 类型有什么作用呢?有人告诉我函数指针被视为 bool,是真的吗?cout 对类型 (void *) 有什么作用?

提前致谢.

无论如何,我们可以通过将函数指针转换为 (void *) 并使用 cout 将其打印出来来观察它的内容.但它不适用于成员函数指针,编译器会抱怨非法转换.我知道成员函数指针是比简单指针更复杂的结构,但是如何观察成员函数指针的内容呢?

解决方案

实际上存在一个

重载的 <<看起来像这样的运算符:

ostream &运算符 <<( ostream &, const void * );

这符合您的期望 - 以十六进制输出.函数指针不可能有这样的标准库重载,因为它们有无数种类型.所以指针被转换为另一种类型,在这种情况下它似乎是一个布尔值 - 我无法立即记住这个规则.

C++ 标准规定:

<块引用>

4.12 布尔转换

1 算术的右值,枚举、指针或指向成员类型可以转换为bool 类型的右值.

这是为函数指针指定的唯一转换.

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;
}

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?

解决方案

There actually is an overload of the << operator that looks something like:

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 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.

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.

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

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