我不明白那里发生了什么。使用Visual Studio 2008,我定义了这样的枚举:

enum MyType{
    A,
    B,
    C
};

然后,我使用它来初始化成员变量:

class MyClass
{
    private:
        bool   bit_;
        uint16 num_;
        MyType member_;
    public:
        MyClass(MyType value){
            member_ = value; // This the assignment which fails
        } // Here, there's a breakpoint to query member_ value    
};

myClass实例= new myClass();

我正在使用调试配置,因此在阅读变量时,没有任何优化可以欺骗我。在分配后的断点,调试器将Member_的值显示为 member_ = C.

它可能是一个调试器Whatch Refresh问题,但是,在检查时评估正确的方法中:

if(member_ == C){
    // ??
}

而且,分配给其他值会产生奇怪的数字,例如执行 member_ = B 给予 member_ = 258 当它ferch。你能告诉我怎么了吗?提前致谢。

编辑#1

我注意到一个有趣的效果,解释了为什么分配后 member_ = A 表达方式 member_ == C 评估 true 对于具有默认值的枚举:

对于枚举

enum MyType{ A, B, C}; // equivalent to enum MyType{ A = 0, B = 1, C = 2};

我明白了

MyType  a = A; // but when fetching a the value is   2  (0x0002)  thats the map for C!
MyType  b = B; // but when fetching a the value is 258  (0x0102)
MyType  c = C; // but when fetching a the value is 514  (0x0202)

但是如果我做

enum MyType{ A = 5, B = 6, C = 7};

我明白了

MyType  a = A; // but when fetching a the value is 1282  (0x0502)
MyType  b = B; // but when fetching a the value is 1538  (0x0602)
MyType  c = C; // but when fetching a the value is 1794  (0x0702)

因此,在分配#?!^%枚举时,该规则似乎是Shift 8位并添加2。这听起来像编译器问题。

顺便说一句 member_ 成为 int 反而 MyType 什么都没有改变。

编辑#2在课堂上增加了两个成员,这是问题的真正原因。时间限制消失后,我将立即发布答案(问题的发布为8h)。

有帮助吗?

解决方案 2

感谢大家。工作中的某人指出了问题的起源。

这是该项目配置错误的问题,这给出了数据对齐问题。

编译后,使用当前的项目设置,课程的两个第一个成员是大小的3个字节。

它应该是4个字节,因此是1个字节的未对准。添加的额外2是在未对准字节处的垃圾,因此,整体效果是移动一个字节并添加2。

尽管不是一个优雅的解决方案(解决方案是为了配置项目),但这种效果是取消添加的,尽管它不是一个优雅的解决方案)。

class MyClass
{
    private:
        bool   bit_;  // 1 byte
        uint16 num_;  // 2 byte

        bool dummy;   // extra byte to help the alignment

        MyType member_;
    public:
        MyClass(MyType value){
            member_ = value; // Now it works as expected.
        }
};

其他提示

ENUM条目不必具有唯一的值。您可能有一个枚举A,B,C,其中A和C等于“ 42”。在这种情况下,当VAR的值为42时,IDE 只会告诉你一个 在匹配条目中,A或C,不是两者兼而有之。

您可以轻松地创建具有“重复”条目的枚举,例如:

enum { A=1, B=1, C=1 }

但是很可能您不是那样做。但是,使用自动化时,您也可以意外(或故意)创建重复项:

enum { A, B, C }       // 0,1,2
enum { A, B, C=0 }     // 0,1,0
enum { A=2, B=1, C }   // 2,1,2
enum { A=-1, B, C=0 }  // -1,0,0

确保仔细检查您的枚举定义。

看到IE http://www.learncpp.com/cpp-tutorial/45-enumerated-types/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top