[英]Assigning to [custom typdef] from incompatible type 'int'
In a method in my main.c file, I declare the variable irq_raised, which is of the type irq_type. 在我的main.c文件中的方法中,我声明了变量irq_raised,它的类型为irq_type。 I've defined irq_type in a typedef in another file and #import it at the top of main.c.
我在另一个文件的typedef中定义了irq_type,并在main.c的顶部#import它。
typedef enum
{
IRQ_NONE = 0x0000,
IRQ_VBLANK = 0x0001,
IRQ_HBLANK = 0x0002,
IRQ_VCOUNT = 0x0004,
IRQ_TIMER0 = 0x0008,
IRQ_TIMER1 = 0x0010,
IRQ_TIMER2 = 0x0020,
IRQ_TIMER3 = 0x0040,
IRQ_SERIAL = 0x0080,
IRQ_DMA0 = 0x0100,
IRQ_DMA1 = 0x0200,
IRQ_DMA2 = 0x0400,
IRQ_DMA3 = 0x0800,
IRQ_KEYPAD = 0x1000,
IRQ_GAMEPAK = 0x2000,
} irq_type;
I can assign this variable to one of these like so: 我可以将此变量分配给其中一个,如下所示:
irq_raised = IRQ_NONE;
However, when I attempt to do the following: 但是,当我尝试执行以下操作时:
irq_raised |= IRQ_HBLANK;
I get the error: 我收到错误:
Assigning to 'irq_type' from incompatible type 'int'
Why is this? 为什么是这样?
In C++ you cannot assign an int directly to an enumerated value without a cast. 在C ++中,如果没有强制转换,则无法将int直接赋值给枚举值。 The bitwise OR operation you are performing results in an int, which you then attempt to assign to a variable of type
irq_type
without a cast. 您正在执行的按位OR运算会产生一个int,然后您尝试将其分配给
irq_type
类型的变量而不使用irq_type
。 It is the same problem as you would have here: 这与你在这里遇到的问题是一样的:
irq_type irq = 0; // error
You can cast the result instead: 您可以转换结果:
irq_type irq = IRQ_NONE;
irq = (irq_type)(irq | IRQ_HBLANK);
Relevant info from the specification: 规范中的相关信息:
An enumerator can be promoted to an integer value.
枚举器可以提升为整数值。 However, converting an integer to an enumerator requires an explicit cast, and the results are not defined.
但是,将整数转换为枚举器需要显式强制转换,并且未定义结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.