huangblue / c

0 stars 0 forks source link

怎样使用typedef建立新类型【C全面326(347)】 #50

Open huangblue opened 7 years ago

huangblue commented 7 years ago

To define a new type name with typedef, follow these steps:

  1. Write the statement as if a variable of the desired type were being declared.
  2. Where the name of the declared variable would normally appear, substitute the new type name.
  3. In front of everything, place the keyword typedef.

    1 按一般方法,定义指定类型的变量 2 将变量名作为新的类型名 3 在前面添加typedef

    实质就是为原来的类型取一个新名字,就是原类型的别名。

huangblue commented 7 years ago

例1: typedef int Counter; 这个定义,为int 取了一个别名Counter

1 定义一个int变量x int x;

2 将变量名改为新的类型名: int Counter;

3 在前面加typedef

typedef int Counter;

或者,我们直接省略掉第2步,开始就把新的类型名定义为int 变量: int Counter; 再加上typedef: typedef int Counter;

以后,就可以用Counter定义变量了,例如: Counter i,j;

huangblue commented 7 years ago

例2: typedef char Linebuf [81]; 这里,将Linebuf定义为有81个元素字符数组类型。

1 char Linebuf[81]; 2 typedef char Linebuf[81];

以后可以用Linebuf来定义字符数组了,形式上看是变量,实际上是数组: Linebuf text, inputLine;

相当于: char text[81],inputLine[81];

huangblue commented 7 years ago

例3:typedef char *StringPtr;

1 char StringPtr; 2 typedef char StringPtr;

这个语句,将StringPtr定义为字符串数组类型 StringPtr buffer; 实际上相当于 char *buffer;

看起来并不省,但别名的好处是它有更明确的含义。

huangblue commented 7 years ago

例4: typedef struct { int month; int day; int year; } Date;

1 struct { int month; int day; int year; } Date;

2 typedef struct { int month; int day; int year; } Date;

这样将指定的结构取了一个别名Date,以后就可以用它来定义变量,数组等,如:

Date birthdays[100];

huangblue commented 7 years ago

例5: typedef struct { float x; float y; } Point;

1 struct { float x; float y; } Point;

2 typedef struct { float x; float y; } Point;

用别名Point定义变量: Point origin = { 0.0, 0.0 }, currentPoint;

huangblue commented 7 years ago

对比一下结构本来的定义:

struct month { int numberOfDays; char name[3]; }; 这里定义一个结构month,要定义这个结构的变量,用下面的语句: struct month aMonth;

而直接定义结构变量(将上面两步合在一起),是下面这个样子: struct date { int month; int day; int year; } todaysDate, purchaseDate;

如果定义一个: struct date { int month; int day; int year; } todaysDate;

结构名可以省略掉: struct { int month; int day; int year; } todaysDate; 这样以后就不能定义这种结构的变量了(因为结构没有名字)。 而我们把这种定义中的变量名作为别名: struct { int month; int day; int year; } Date;

就引导到typedef用在结构上的办法了:

typedef struct { int month; int day; int year; } Date;

对结构使用typedef,必须把结构的定义写全,第一步是匿名的结构变量定义,第二步加上typedef。