c++ - 指向两个不同结构的指针

标签 c++ pointers structure

我有三个结构headerdataAdataBheader 将决定将要使用的结构。 dataAdataB 具有几乎相同的结构(比方说):

struct dataA
{
    int   intValue;
    char  reserved1[8];
    float floatValue;
    char  reserved2[4];
    short shortValue;
};

struct dataA
{
    int   intValue;
    short shortValue;
    char  reserved[2];
    float floatValue;
};

我想像这样打印它:

sprintf(outStr, "%i, %f, %s", p->intValue, p->floatValue, p->shortValue);

-- 或者 --

sprintf(outStr, "%i, %f, %s", p.intValue, p.floatValue, p.shortValue);

如何声明p? (注意: dataAdataB 都有很大的结构,但数据几乎相同,除了那些保留的 值。)

我是这样想的:

void * p;

if (header->type==1)
   p = (dataA*)(pData);
else if (header->type==2)
   p = (dataB*)(pData);

// print all data here

注意: 这里的 pData 是指向我将读取的(原始)数据的指针。我只需要那些非保留值,而忽略保留值。

最佳答案

将打印逻辑移动到函数模板中:

template <typename T>
int print_data(char* const str, std::size_t const len, T const* const p)
{
    return std::snprintf(
        str, len,
        "%i, %f, %s",
        p->intValue, p->floatValue, p->shortValue);
}

然后从你的切换逻辑中调用这个函数:

if (header->type==1)
    print_data(str, len, static_cast<dataA const*>(pData));
else if (header->type==2)
    print_data(str, len, static_cast<dataB const*>(pData));

如果您计划使用 std::snprintf,最好将 static_assert 添加到 print_data 函数模板以确保 T 的数据成员类型是您期望的类型,只是为了确定。

请注意,如果您的平台有严格的对齐要求,并且不能保证 pData 指向的数据对于您的所有目标类型都正确对齐,您将需要用一个拷贝替换强制转换字节放入适当对齐的缓冲区。

关于c++ - 指向两个不同结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11337678/

相关文章:

c++ - 定义数组时是否可以接受const_cast?

c++ - 使用 std::pair 类的头文件中的 typedef 错误

c - 如果某些限制指针指向同一个对象,为什么编译器不生成警告或错误?

c - 结构和 memcpy 警告

c++ - 使用 Eigen 库存储 3D 数据

c++ - 如何在不丢失现有数据的情况下调整 std::vector 的大小?

arrays - 函数中 str[strlen(src)+1] 和 char *str=(char*)malloc((strlen(src)+1)*sizeof(char)) 的区别

C 指向指针的指针和按引用传递

c++ - 如何在类中定义结构?

找到时无法返回树节点