【问题标题】:Pointer to two different structures指向两个不同结构的指针
【发布时间】:2012-07-05 03:55:12
【问题描述】:

我有三个结构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 是一个指向我将被读取的(原始)数据的指针。我只需要那些非保留 值,而忽略保留 值。

【问题讨论】:

  • 你能改变类型定义吗?

标签: c++ pointers structure


【解决方案1】:

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

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_asserts 添加到print_data 函数模板中,以确保T 的数据成员的类型是您期望的类型,只是为了确定。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 2013-12-13
    • 1970-01-01
    • 2019-03-18
    相关资源
    最近更新 更多