gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:31 28 4
gpt4 key购买 nike

我在结构中有一个枚举:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com