您的位置:首页 > 其它

struct/enum/union用法

2014-12-17 14:53 344 查看
(文章参考了网上其它文章,基本不是原创)

1.定义及声明

1.1只定义类型名

type type_name

{
...

};

eg.

enum my_enum

{
a,
b,
c

};

1.2定义并声明变量

type type_name

{
...

}object1_name, object2_name;

eg.

union my_union

{
int a;
char b;

}u1;

1.3给类型定义新名

typedef type type_name

{
...

}new_type_name;

1.4 类型匿名

type 

{

...

}object1_name, object2_name;

声明时没有定义类型名需要直接定义变量。因为没有类型名,后面无法再定义该结构的变量,所以声明时定义了多少个该结构的变量,整个工程里就只有这么多的变量。

eg.

struct

{
int a;
char c;

}s1, s2;

在struct中定义的union或者在union中定义的struct就经常用这种方式来定义,因为整个type里就只有这么一个结构,根本不需要为其定义类型名。

eg.

struct {

  char title[50];

  char author[50];

  union {

    float dollars;

    int yen;

  } price;

} book;

这时访问union里的成员跟我们平时访问union成员的方式是一样的。

book.price.dollars

book.price.yen

1.5 typedef + 类型匿名

typedef type 

{

...

}new_type_name;

1.4节使用类型匿名在声明时必须定义变量,而且后面无法再定义同结构的变量。

但使用 typedef + 类型匿名 的方法,即使在声明时不定义类型名,后面还可以继续用typedef定义的别名来定义同结构的变量。

eg.

typedef struct

{
int a;
char c;

}ms_t;

ms_t s1 = { 1, 2 };

2 struct编程技巧

2.1 初始化时可以通过 .xxx 来引用成员名给结构体成员赋值;

一般情况下,定义完struct后,赋值方法如下:

struct s_tag

{
int a;
int b;
int c;

};

struct s_tag s = { 1, 2, 3};

我们可以在初始化时直接引用结构体里的名字对其成员直接赋值:

struct s_tag s = { 
.a = 1,
.b = 2,
.c = 3
};

2.2 完全匿名struct

完全匿名struct只能使用在union中。

#define DUMMYSTRUCTNAME

 

typedef union _LARGE_INTEGER {

 

    struct {

        DWORD LowPart;

        LONG HighPart;

    } DUMMYSTRUCTNAME;

 

    struct {

        DWORD LowPart;

        LONG HighPart;

    } u;

 

    LONGLONG QuadPart;

 

} LARGE_INTEGER;

访问方式如下:

LARGE_INTEGER liFileSize ;

liFileSize.u.LowPart  = 1000 ;

liFileSize.u.HighPart = 2000 ;

LARGE_INTEGER liFileSize ;

liFileSize.LowPart  = 1000 ;

liFileSize.HighPart = 2000 ;

举个例子.

3. enum编程技巧

3.1 用完全匿名enum来定义多个const常量

enum

{
a = 1,
b = 20,
c = 80

};

这种定义方式跟如下定义方式一样。

#define a 1

#define b 20

#define c 80

但毫无疑问,使用enum定义更加优雅一些。

4.union编程技巧

4.1 完全匿名union

完全匿名union只能使用在struct中。

struct {

  char title[50];

  char author[50];

  union {

    float dollars;

    int yen;

  };

} book;

对匿名union结构可以直接引用其成员名来访问:

book.dollars

book.yen

struct中的完全匿名union可以用来提高struct结构体中的数据类型兼容能力。

举个例子。

A要传递一个结构体s给B。s的基本内容如下:

struct s_tag

{
int a;
type x;

};

有时type x是struct type_a, 有时是struct type_b,有时是struct type_b.

我们可以分别定义三个结构体

struct s_tag

{
int a;
type_a var_a;

};

struct s_tag

{
int a;
type_b var_b;

};

struct s_tag

{
int a;
type_c var_c;

};

但是这样写的结果是传递函数的接口也要做相应的更改。

如果我们使用匿名union,可以写成

struct s_tag

{
int a;

int type;
union
{
type_a var_a;
type_b var_b;
type_c var_c;
};

}

这样,当我们要传递type_a时,只需把type_a的值赋值给var_a即可。当我们要传递type_b时,只需把type_b的值赋值给var_b即可。然后赋值给type.这样发送函数的接口就不用更改。

接收的函数可以用type变量来识别我们传递了哪种类型的数据

if( type == type_a )

{
...

}

else if( type == type_b)

{

...

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: