引用枚举枚举返回错误的价值
Reference to cast enumeration returns wrong value
考虑以下代码:
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;
相关文章:
- 错误:从"int"到枚举c++的转换无效
- C++:枚举:错误:应使用标识符而不是"}"
- 无法找到简单的开关大小写枚举错误
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- C++/错误:表达式必须具有整数或无作用域枚举类型
- 如何摆脱C++中的枚举不匹配错误?
- C++ 在方程中使用变量;错误:表达式必须具有整数或无作用域枚举类型及其他
- 枚举输出的值错误
- 枚举成员不是类型错误
- C++ Visual Studio 调试器枚举错误
- 比较枚举的值会给出编译器错误
- C++中一个非常简单的枚举类错误
- 如何编写一个错误结构,该结构可以包含不同的强键枚举作为错误代码
- Bjarne Stroustrup PPP - 第 9 章 演练 4 - cout 枚举错误
- 错误:以增量方式填充向量时,表达式必须具有整数或无作用域枚举类型
- c++开关枚举错误
- OpenGL 创建 glShaderObject 时出现无效枚举错误
- 从limemmicro编译lms6suite时出现枚举错误
- 试图读取枚举状态时c++枚举错误