我对C和C ++的typedef枚举语法有点熟悉。我现在正在使用Objective-C进行编程,并在以下示例中遇到了语法。我不确定语法是否特定于Objective-C。但是,我的问题在以下代码段中,1 << 0
之类的语法是什么意思?
typedef enum {
CMAttitudeReferenceFrameXArbitraryZVertical = 1 << 0,
CMAttitudeReferenceFrameXArbitraryCorrectedZVertical = 1 << 1,
CMAttitudeReferenceFrameXMagneticNorthZVertical = 1 << 2,
CMAttitudeReferenceFrameXTrueNorthZVertical = 1 << 3
} CMAttitudeReferenceFrame;
答案 0 :(得分:11)
这在C语言系列中很常见,在C,C ++和Objective-C中的工作方式相同。与Java,Pascal和类似语言不同,C enum不限于为其命名的值;它实际上是一个可以表示所有命名值的大小的整数类型,并且可以将枚举类型的变量设置为枚举成员中的算术表达式。通常,使用位移来使值的幂为2,并且使用逐位逻辑运算来组合值。
typedef enum {
read = 1 << 2, // 4
write = 1 << 1, // 2
execute = 1 << 0 // 1
} permission; // A miniature version of UNIX file-permission masks
同样,位移操作全部来自C。
您现在可以写:
permission all = read | write | execute;
您甚至可以在权限声明中包含该行:
typedef enum {
read = 1 << 2, // 4
write = 1 << 1, // 2
execute = 1 << 0, // 1
all = read | write | execute // 7
} permission; // Version 2
如何为文件启用execute
?
filePermission |= execute;
请注意,这很危险:
filePermission += execute;
这会将值all
更改为8
,这没有任何意义。
答案 1 :(得分:5)
<<
被称为左移运算符。
http://www.techotopia.com/index.php/Objective-C_Operators_and_Expressions#Bitwise_Left_Shift
长话短1 << 0 = 1
,1 << 1 = 2
,1 << 2 = 4
和1 << 3 = 8
。
答案 2 :(得分:3)
看起来typedef
表示位字段值。 1 << n
1
向左移n
位。因此,每个enum
项表示不同的位设置。该特定位设置或清除将指示某些东西是两种状态之一。左移{0}的1
为1
。
如果声明了原点:
CMAttitudeReferenceFrame foo;
然后,您可以使用enum
值检查四个独立状态中的任何一个,foo
不大于int
。例如:
if ( foo & CMAttitudeReferenceFrameXArbitraryCorrectedZVertical ) {
// Do something here if this state is set
}