【c及c++学习笔记】typedef的妙用

来源:互联网 发布:mac中安装好ruby环境 编辑:程序博客网 时间:2024/05/09 06:34

 typedef的妙用
 
typedef给你一种方式来克服“*只适合于变量而不适合于类型”的弊端。你可以如下使用typedef:
 
typedef char * PCHAR;
PCHAR p,q;
 
这里的 p 和 q 都被声明为指针。(如果不使用 typedef,q 将被声明为一个 char 变量,这跟我们的第一眼感
觉不太一致!)下面有一些使用typedef的声明,并且给出了解释:
 
typedef char * a;  // a is a pointer to a char

typedef a b();     // b is a function that returns
                   // a pointer to a char
 
typedef b *c;      // c is a pointer to a function
                   // that returns a pointer to a char
 
typedef c d();     // d is a function returning
                   // a pointer to a function
                   // that returns a pointer to a char
 
typedef d *e;      // e is a pointer to a function 
                   // returning  a pointer to a            

 // function that returns a  

   // pointer to a char
 
e var[10];         // var is an array of 10 pointers to 
                   // functions returning pointers to 
                   // functions returning pointers to chars.
 
typedef经常用在一个结构声明之前,如下。这样,当创建结构变量的时候,允许你不使用关键字struct(在
C中,创建结构变量时要求使用struct关键字,如struct tagPOINT a;而在C++中, struct可以忽略,如tagPOINT
b)。
 
typedef struct tagPOINT
{
    int x;
    int y;
}POINT;
 
POINT p; /* Valid C code */

原创粉丝点击