c++ - 打印指向成员字段的指针

标签 c++ printf standards-compliance 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 和 0。我认为数字表示字段在 struct 中的位置(即 1y0x),但不是,打印的值实际上是非空指针的 1 和空指针的 0。我想这是一种符合标准的行为(即使它没有帮助)——我说得对吗?此外,兼容的 c++ 实现是否有可能为指向成员的指针始终打印 0?甚至是一个空字符串?

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

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!

有什么更好的方法吗?

最佳答案

指向成员的指针并不像您想象的那么简单。它们的大小随编译器和类的不同而变化,具体取决于类是否具有虚方法以及是否具有多重继承。假设它们是 int 大小不是正确的方法。你可以做的是以十六进制打印它们:

void dumpByte(char i_byte)
{
    std::cout << std::hex << static_cast<int>((i_byte & 0xf0) >> 4);
    std::cout << std::hex << static_cast<int>(i_byte & 0x0f));
} // ()

template <typename T>
void dumpStuff(T* i_pStuff)
{
    const char* pStuff = reinterpret_cast<const char*>(i_pStuff);
    size_t size = sizeof(T);
    while (size)
    {
        dumpByte(*pStuff);
        ++pStuff;
        --size;
    } // while
} // ()

但是,我不确定这些信息对您有多大用处,因为您不知道指针的结构是什么以及每个字节(或几个字节)的含义。

关于c++ - 打印指向成员字段的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7826985/

相关文章:

c++ - 如何检查是否设置了 std::string?

c++ - printf 与 long long int 的结果不一致?

基于非 IEEE 754 : is such C compiler C standard compliant? 的 C 编译器的 FP

flutter - 可以将 Flutter 用于符合 Hipaa 的应用程序吗?

c++ - 在 C++ 中不使用 cmath 计算 n 次根的有效方法

c++ - 使用opencv c++对相同的面孔进行分组

c - 如何在 C 中使用数组

c - 将 printf 移动到不同的行会产生不同的输出? (C)

html - CSS 等高列 - 呃!再次?

c++ - png_read_image 访问冲突?