typedef 结构体用法 [英] typedef struct usage

查看:36
本文介绍了typedef 结构体用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能说我使用了很多 typedef,但是在 Cocoa Touch 中,它有点令人困惑.以 CoreGraphics 自己对 CGPoint 的定义为例:

I can't say I've used a lot of typedefs, but in Cocoa Touch, it's is a little confusing. Take for instance CoreGraphics' own definition for CGPoint:

struct CGPoint {
    CGFloat x;
    CGFloat y;
};
typedef struct CGPoint CGPoint;

如果我要根据我在书中看到的内容来定义这一点,请转到:

If I were to define this from what I've seen in books, go:

typedef struct {
    CGFloat x;
    CgFloat y;
} CGPoint; 

而且它似乎工作得很好.那么这些在做什么有什么不同,还是在做完全相同的事情?

and it seems to be working perfectly fine. So is there a difference in what these are doing, or are these doing the exact same thing?

推荐答案

Apple 的示例与此相同.

Apple's example is the same as doing this.

typedef struct CGPoint {
    CGFloat x;
    CGFloat y;
} CGPoint;

不同之处在于,在 Apple 定义的代码中,您可以将变量定义为 struct CGPointCGPoint.在您的 typedef 中,您基本上创建了一个无名结构,然后您将其称为 CGPoint,而不是一个名为 CGPoint 的结构,您也将其称为 CGPoint.

The difference is that in code with Apple's definition, you could define a variable as either struct CGPoint OR CGPoint. In your typedef you have basically created a nameless struct, that you then call a CGPoint, rather than a struct named CGPoint that you also call a CGPoint.

通常你会看到 typedef 的 'struct' 部分被替换为类似 CGPoint_t

Often you will see typedefs have the 'struct' part replaced with something like CGPoint_t

考虑以下内容.

typedef struct {
    List *next;  // <-- compiler error
} List;

为什么?因为编译器还不知道类型List".

Why? Because the type 'List' isn't known to the compiler yet.

typedef struct List {
    struct List *next; // <-- works because you named your struct, and used that name here
} List;

如果不命名结构,则不能将其自身(指针)作为成员包含在内.

If you do not name your struct, you cannot include itself (pointer) as a member.

这篇关于typedef 结构体用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆