引用枚举枚举返回错误的价值

Reference to cast enumeration returns wrong value

本文关键字:枚举 错误 返回 引用      更新时间:2023-10-16

考虑以下代码:

enum TestEnum
{
   TEST_ENUM_5 = 5
};
class Test
{
public:
   Test() { mType = TEST_ENUM_5; mVal = 1; }
   TestEnum& type() { return (TestEnum&)mType; }
private:
   uint16_t mType;
   uint16_t mVal;
};
int main( int argc, const char* argv[] )
{
   Test test;
   assert( test.type() == TEST_ENUM_5 );
}

该程序通过MSVC 2010编译罚款 - 没有错误或警告。但是断言失败 - 返回的值不是5,而是0x00010005。

换句话说,返回的枚举的值解释为4个字节值 - 包括以下简短的内容。我可以明白为什么编译器这样做,参考是对MTYPE的地址的参考,并且正在加载一个寄存器。

但是,这种编译器的正确行为是正确的吗?

不应该知道TestEnum&是对16位数量的引用吗?或者,如果不想这样做,它不应该警告吗?

除此之外,我想做的就是将简短的枚举存储到16位值中,并具有返回对其的引用的方法,该方法是键入的。从逻辑上讲,我想要的是一个允许我的接口:

test.type() = TEST_ENUM_5;

并在编译时知道它只有预期来自testEnum的值。为此,我希望该类用户阅读该课程以了解在这里可以知道测试值。

您说枚举必须是两个字节,而 type()的返回类型必须是枚举参考。

c 11具有一个功能,您可以在其中指定枚举的基本类型:

enum TestEnum : unsigned short
{
   TEST_ENUM_5 = 5
};
   TestEnum& type() { return mType; }
private:
   TestEnum mType;

好吧,如果您需要这样的用法test.type() = TEST_ENUM_5;,只需正确地实现它:

   Test() { mType = TEST_ENUM_5; mVal = 1; }
   TestEnum& type() { return mType; }
private:
   TestEnum mType;

upd:" 2 bytes"版本:

   Test() { mType = TEST_ENUM_5; mVal = 1; }
   uint16_t& type() { return mType; }
private:
   uint16_t mType;