c++ - 枚举被定义为结构中的 uint8_t 变量

标签 c++ c qt-creator

我在结构中有一个枚举:

enum Days : uint8_t
{
  day1 =1,
  day2 =2,
  day2 =3
}

struct Hi
{
  Days days;
}

在编译时,我收到错误 Scoped enums not available in this version。 我需要我所有的枚举都是 uint8_t 类型并在结构中定义。

最佳答案

即使在 C++11 之前,如果您注意所有枚举值都小于 128,您可以简单地将它们存储在一个 uint8_t 变量中。不过,这可能需要在使用时进行转换。这是将枚举值压缩到结构中的常用方法,尤其是在内存紧张的嵌入式代码中。如果您的代码使用这些结构的大量实例,这种技术还可以提高您的数据缓存命中率。

enum Days
{
    Day1 =1,
    Day2 =2,
    Day3 =3
};
typedef uint8_t DaysTy;

// Totally optional, but allows you to send a 'DaysTy' to cout directly:
std::ostream& operator<<(std::ostream& s, const DaysTy& d)
{
    const char* txt="ILLEGAL";
    switch (d)
    {
        case Day1: txt = "Day1"; break;
        case Day2: txt = "Day2"; break;
        case Day3: txt = "Day3"; break;
    }
    s << txt;
    return s;
}

struct Hi
{
    DaysTy dayA;
    DaysTy dayB;
    DaysTy dayC;

    // Totally optional, but allows you to send a 'Hi' struct to cout directly:
    friend std::ostream& operator<<(std::ostream& s, const Hi& m);
};

// Totally optional, but allows you to send a 'Hi' struct to cout directly:
std::ostream& operator<<(std::ostream& s, const Hi& h)
{
    s << '[' << h.dayA << ',' << h.dayB << ',' << h.dayC << ']';
    return s;
}


int main()
{
    Hi aHiObject;
    aHiObject.dayA = Day3;
    aHiObject.dayB = Day2;
    aHiObject.dayC = Day1;

    std::cout << "my Hi object: " << aHiObject << '\n';
    if (aHiObject.dayA == Day1)
        std::cout << "Its dayA is Day1.\n";
    if (aHiObject.dayA == Day2)
        std::cout << "Its dayA is Day2.\n";
    if (aHiObject.dayA == Day3)
        std::cout << "Its dayA is Day3.\n";

    std::cout << "sizeof(aHiObject)      = " << sizeof(aHiObject) << " byte(s)\n"
                 "sizeof(aHiObject.dayA) = " << sizeof(aHiObject.dayA) << " byte(s)\n";

    std::cout << "Value '3' as a uint8_t: " << (uint8_t)3 << '\n';
    std::cout << "Value '3' as a DaysTy: "  << (DaysTy)3  << '\n';

    std::cout << "Value '4' as a uint8_t: " << (uint8_t)4 << '\n';
    std::cout << "Value '4' as a DaysTy: "  << (DaysTy)4  << '\n';
}

运行这段代码会产生这样的输出:

my Hi object: [Day3,Day2,Day1]
Its dayA is Day3.
sizeof(aHiObject)      = 3 byte(s)
sizeof(aHiObject.dayA) = 1 byte(s)
Value '3' as a uint8_t: Day3
Value '3' as a DaysTy: Day3
Value '4' as a uint8_t: ILLEGAL
Value '4' as a DaysTy: ILLEGAL

...这顺便表明下面 Mike Seymour 的评论是正确的。不过,这展示了一种将枚举值打包为 uint8_t 变量类型的方法。

关于c++ - 枚举被定义为结构中的 uint8_t 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18235801/

相关文章:

qt - Qt Creator 将其设置保存在哪里?

c++ - Valgrind 合法的 "possibly lost"字节示例

c++ 将存储在 std::vector 中的数据传递给 c_func(void* data)

c++ - LLDB 有时显示 vector 数据,有时不显示

c++ - 如何使用 C++ 检查进程是否正在运行

c++ - Qt Creator如何重新定义getter和setter函数的创建方式?

c - 警告 : Suspicious pointer-to-pointer conversion (area too small) with lint

gdb 可以调试 gcc 风格的嵌套 C 函数吗?

c - 基本链接描述文件

c++ - CMakeLists.txt中的安装目录,适用于Visual Studio和Qt Creator