打印指向成员字段的指针 [英] Printing a pointer-to-member-field

查看:83
本文介绍了打印指向成员字段的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调试一些涉及到成员字段指针的代码,因此我决定将它们打印出来以查看其值.我有一个函数返回一个指向成员的指针:

I was debugging some code involving pointers to member fields, and i decided to print them out to see their values. I had a function returning a pointer to member:

#include <stdio.h>
struct test {int x, y, z;};
typedef int test::*ptr_to_member;
ptr_to_member select(int what)
{
    switch (what) {
    case 0: return &test::x;
    case 1: return &test::y;
    case 2: return &test::z;
    default: return NULL;
    }
}

我尝试使用cout:

#include <iostream>
int main()
{
    std::cout << select(0) << " and " << select(3) << '\n';
}

我得到了1 and 0.我以为数字表示该字段在struct内部的位置(即1y0x),但是不,对于非空指针,0表示空指针.我猜这是一种符合标准的行为(即使它没有帮助)-是吗?另外,兼容的c ++实现是否可以始终为成员指针打印0?甚至是空字符串?

I got 1 and 0. I thought the numbers indicated the position of the field inside the struct (that is, 1 is y and 0 is x), but no, the printed value is actually 1 for non-null pointer and 0 for null pointer. I guess this is a standard-compliant behavior (even though it's not helpful) - am i right? In addition, is it possible for a compliant c++ implementation to print always 0 for pointers-to-members? Or even an empty string?

最后,我该如何以有意义的方式打印指向成员的指针?我想出了两种丑陋的方法:

And, finally, how can i print a pointer-to-member in a meaningful manner? I came up with two ugly ways:

printf("%d and %d\n", select(0), select(3)); // not 64-bit-compatible, i guess?

ptr_to_member temp1 = select(0); // have to declare temporary variables
ptr_to_member temp2 = select(3);
std::cout << *(int*)&temp1 << " and " << *(int*)&temp2 << '\n'; // UGLY!

还有更好的方法吗?

推荐答案

成员指针不是普通的指针.实际上,您没有期望的<<重载.

Member pointers aren't ordinary pointers. The overloads you expect for << aren't in fact there.

如果您不介意进行类型调整,则可以破解一些东西以打印实际值:

If you don't mind some type punning, you can hack something up to print the actual values:

int main()
{
  ptr_to_member a = select(0), b = select(1);
  std::cout << *reinterpret_cast<uint32_t*>(&a) << " and "
            << *reinterpret_cast<uint32_t*>(&b) << " and "
            << sizeof(ptr_to_member) << '\n';
}

这篇关于打印指向成员字段的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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