我对 C 和 C++ 的 typedef 枚举语法有些熟悉。我现在正在使用 Objective-C 进行编程,并遇到了以下示例中的语法。我不确定语法是否特定于 Objective-C。但是,我的问题是在下面的代码片段中,像 1 << 0
这样的语法是什么?什么意思?
typedef enum {
CMAttitudeReferenceFrameXArbitraryZVertical = 1 << 0,
CMAttitudeReferenceFrameXArbitraryCorrectedZVertical = 1 << 1,
CMAttitudeReferenceFrameXMagneticNorthZVertical = 1 << 2,
CMAttitudeReferenceFrameXTrueNorthZVertical = 1 << 3
} CMAttitudeReferenceFrame;
这在 C 语言家族中很常见,并且在 C、C++ 和 Objective-C 中的工作方式相同。与 Java、Pascal 和类似语言不同,C 枚举不限于为其命名的值;它实际上是一个整数类型,其大小可以表示所有命名值,并且可以将枚举类型的变量设置为枚举成员中的算术表达式。通常,一种方法是使用位移位来使值成为 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
,这是没有意义的。