[英]With typedef enum, return type enum EnumName produces compiler error when returning an enum member
[英]enum Not Type Checked by Compiler?
有了这些枚举......
typedef enum {
ThisThingA = 0,
ThisThingB = 1
} ThisThing;
typedef enum {
ThatThingX = 8,
ThatThingY = 9
} ThatThing;
和这些属性......
@property (nonatomic) ThisThing thisThing;
@property (nonatomic) ThatThing thatThing;
我可以做这个...
self.thisThing = thatThingX;
而且我没有得到编译器的警告,我希望如此。 为什么编译器没有警告? 为什么我可以将类型为ThatThing的东西分配给ThisThing类型的东西?
根据Martin R的回答编辑:但如果我这样做......
[self setThisThing:thatThingX];
我收到警告:从枚举类型'ThatThing'到不同的枚举类型'ThisThing'的隐式转换
(Xcode 4.6.3和iOS 6.0)
默认情况下,编译器选项“Implicit Enum Conversions(-Wenum-conversion)”处于启用状态,如果您指定了不同枚举类型的变量,则实际上会收到警告:
ThisThing x = ThatThingX;
或者如果使用setter方法设置属性:
[self setThisThing:ThatThingX];
在这两种情况下,您都会收到警告
implicit conversion from enumeration type 'ThatThing' to different enumeration type 'ThisThing' [-Wenum-conversion]
仅当您使用“点”语法设置值时
self.thisThing = ThatThingX;
然后你没有得到警告,所以这可能是编译器中的一个错误。
enum是C构造,它是一个整数类型。 它是类型检查。 您的用法是相同的默认整数类型,因此在编译器的眼睛中根本没有任何错误。 你的用法是int。
如果你将typedef int作为Bob并再次作为Josephine,这样可以方便代码清晰度。 鲍勃和约瑟芬仍然是同一类型int。
如果您声明两个枚举但一个使用NSUInteger而另一个使用NSInteger,则可能会收到警告,具体取决于隐式转换的设置。
这真的是一个C问题。
实际上,枚举选项被视为NSInteger。 因此,默认情况下, theThingX的值为0。 当你分配self.thisThing = thatThingX;
self.thisThing的值为0.所以它将成为ThisThingA 。 这就是没有警告的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.