首页 > 解决方案 > 在 C++ 中为 struct(union) 创建构造函数

问题描述

为结构(具有联合成员,有关系吗?)创建构造函数以将uint8_t类型转换为结构的最佳方法是什么?

这是我的示例以澄清更多信息:

struct twoSixByte
{
    union {
        uint8_t fullByte;
        struct
        {
            uint8_t twoPart : 2;
            uint8_t sixPart : 6;
        } bits;
    };
};

uint32_t extractByte(twoSixByte mixedByte){
  return mixedByte.bits.twoPart * mixedByte.bits.sixPart;
}

uint8_t tnum = 182;
print(extractByte(tnum)); // must print 2 * 54 = 108

PS 从评论和答案中查找,在 C++ 中无法对联合进行类型双关语。

给出的解决方案有点复杂,特别是在代码中有很多这些结构的地方。甚至在某些情况下,一个字节被分成多个位部分(两个以上)。因此,如果不利用联合,而是使用位集和移位位,则会给代码增加很多负担。

相反,我设法找到了一个更简单的解决方案。我只是在将类型传递给函数之前转换了它。这是固定代码:

struct twoSixByte
    {
        union {
            uint8_t fullByte;
            struct
            {
                uint8_t twoPart : 2;
                uint8_t sixPart : 6;
            } bits;
        };
    };

    uint32_t extractByte(twoSixByte mixedByte){
      return mixedByte.bits.twoPart * mixedByte.bits.sixPart;
    }

    uint8_t tnum = 182;
    twoSixByte mixedType;
    mixedType.fullByte = tnum;
    print(extractByte(mixedByte)); // must print 2 * 54 = 108

标签: c++structconstructorarduinounions

解决方案


除非您迫切需要使用 a union,否则不要使用它。将您的课程简化为:

struct twoSixByte
{
   twoSixByte(uint8_t in) : twoPart((in & 0xC0) >> 6), sixPart(in & 0x3F) {}
   uint8_t twoPart : 2;
   uint8_t sixPart : 6;
};

如果需要获取完整字节,可以使用:

uint8_t fullByte(twoSixByte mixedByte)
{
   return ((mixedByte.twoPart << 6) | mixedByte.sixPart);
}

推荐阅读