为 C++ 开发人员在 C 中声明和使用枚举和结构

declaring and using enums and structs with C for C++ developers

我想知道什么时候 typedef 应该与 C 中的 structs/enums 一起使用。 我相信同样的原则适用于 objective-C

假设我有这样的东西

@interface foo : UIViewController
...

enum PlayState {Start , Stop , Pause};

@end

然后在实现文件中我有这个

@implementation foo

-(void) SomeMethod : (PlayState) val  /// <----Eror : How do I set PlayState as a parameter
{
} 
@end

更改枚举声明:

typedef enum : NSUInteger {
    Start,
    Stop,
    Pause,
} PlayState;

C 的乐趣...

在 (Objective-)C 中,由 enum(或 struct)定义引入的名称不是独立的,要使用它,您必须在其前面加上 enum.所以你的例子可以写成:

enum PlayState {Start , Stop , Pause};

- (void) SomeMethod:(enum PlayState)val

C 还允许使用 typedef 为任何类型赋予 shorthand,因此您可以在上面添加:

typedef enum PlayState PlayState;

请注意,这两个 PlayState 是不同的 - 一个是 enum 标识符,另一个是类型名称 - C 总是可以从上下文中分辨出你的意思。

现在您可以使用 PlayState:

- (void) SomeOtherMethod:(PlayState)val

(并且 enum PlayState 仍然有效)。

C 然后允许您将 enumtypedef 合二为一,给出:

typedef enum PlayState {Start , Stop , Pause} PlayState;

最后,由于您现在将 PlayState 作为类型名称,因此您可能永远不会使用 enum PlayState,因此 C 允许您删除标签:

typedef enum {Start , Stop , Pause} PlayState;

enum PlayState 现在不再有效。

以上所有也适用于struct