现在的位置: 首页 > 综合 > 正文

zhiyinjixu总结: typedef 用法终结总结

2012年05月13日 ⁄ 综合 ⁄ 共 2241字 ⁄ 字号 评论关闭

用法:

用法一:
直接代替
typedef int zheng;
例子:两者是等价的
int a;
zheng a;

用法二:
数组
typedef double shuang[5];
例子:两者是等价的
double a[5];
shaung a;

用法三:
指针
typedef int *aaa;
例子:两者是等价的
int *p;
aaa p;

用法四:
指针数组
typedef int *a[5];
例子:两者是等价的
int *zz[5];
a zz;

用法五:
结构型
typedef struct stu
{
long number;
char name[10];
char sex;
} ccc;
例子:两者是等价的
struct stu jack = {3366,"jack", 'm'};
ccc jack = {3364,"tom", 'f'};

用法六:
函数指针类型
typedef int (*FUNC_PTR) (int a, int b);
例子:两者是等价的
int (*pf1) (int a, int b);
FUNC_PTR pf1;

 

typedef的规律 :

type 的规律:
    无论是基本数据类型,还是数组类型、指针类型、指针数组类型、结构型、函数指针类型。它总是符合这样一个规律,就是:
用户类型符(我们将要使用的那个新类型)定义了之后,且用这个新的类型定义了一个变量,如果想要不使用这个新类型,则直接将变量放到这个新类型定义语句中,并替换定义的这个用户类型符,并且去掉typedef,则恢复到了原貌。
    事实上,用户类型符只是变量的一个替身而已,正因为有了typedef这个关键词,它不再是一个变量,而是一个类型。 

例如:
一、基本数据类型
typedef int zheng;     //用户类型符的定义
zheng a;            //用新类型定义变量
要恢复原貌,则直接将变量放到这个新类型定义语句中,并替换定义的这个用户类型符,并且去掉typedef, 即: int a;
二、数组类型
typedef double shuang[5];
shuang b;
要恢复原貌,则直接将变量放到这个新类型定义语句中,并替换定义的这个用户类型符,并且去掉typedef ,即: double b[5];
三、指针类型
typedef int * aaa; 
aaa p;
要恢复原貌,则直接将变量放到这个新类型定义语句中,并替换定义的这个用户类型符,并且去掉typedef ,即:int * p;
四、指针数组类型
typedef int *bbb[5];
bbb z;
要恢复原貌,则直接将变量放到这个新类型定义语句中,并替换定义的这个用户类型符,并且去掉typedef ,即:int *z[5];
五、结构型
typedef struct stu   
{
long number;
char name[10];
char sex;
} ccc;
ccc jack;
要恢复原貌,则直接将变量放到这个新类型定义语句中,并替换定义的这个用户类型符,并且去掉typedef ,即:
struct stu   
{
long number;
char name[10];
char sex;
} jack;
六、函数指针类型
typedef int (*FUNC_PTR) (int a, int b);
FUNC_PTR pf1;
要恢复原貌,则直接将变量放到这个新类型定义语句中,并替换定义的这个用户类型符,并且去掉typedef ,即: int (*pf1) (int a, int b);

 

实例代码:

#include <iostream>
using namespace std;
int x=99;
int y=98;

 int And (int a, int b)
 {
  return (a+b);
 }

int main()
{
 typedef int zheng;
 int a1=6;
    zheng a2=3;   
    cout<<a1<<endl<<a2<<endl;
 cout<<endl;
   
    typedef double shuang[5];
    double aa1[5] = {6};
 shuang aa2 = {7};
 cout<<aa1[0]<<endl<<aa2[0]<<endl;
 cout<<endl;

 typedef int * aaa;  //注意:* 是和aaa是一起的,该句和   typedef int (* aaa); 是等价的。就和上面的数组typedef 是一样的
 int *p1 = &x;
 aaa p2 = &x;
 cout<<p1<<endl<<p2<<endl;
 cout<<endl;

 typedef int *bbb[5];
 int *zz1[5];
 zz1[0] = &y;
 bbb zz2;
 zz2[0] = &y;
 cout<<zz1[0]<<endl<<zz2[0]<<endl;
 cout<<endl;

 typedef struct stu   //注意:要用typedef,则这个结构型可以是无名结构型
 {
 long number;
 char name[10];
 char sex;
 } ccc;
 struct stu jack = {3366,"jack", 'm'};
 cout<<jack.sex<<endl;
 ccc tom = {3364,"tom", 'f'};
 cout<<tom.sex<<endl;

 int And (int a, int b) ;
 typedef int (*FUNC_PTR) (int a, int b);
 FUNC_PTR pf1 = And;
 cout<<And<<endl;
 cout<<pf1<<endl;
 cout<< And (1,2)<<endl;
 

 return 0;
}

 

 

 

 

 

 

 

 

 

 

 









抱歉!评论已关闭.