typedef 及其与struct的结合使用

 2023-09-19 阅读 13 评论 0

摘要:1 //相当于为现有类型创建一个别名,或称类型别名。 2 //整形等 3 typedef int size; 4 5 6 //字符数组 7 char line[81]; 8 char text[81];//=> 9 10 typedef char Line[81]; 11 Line text, secondline; 12 13 14 //指针 15 typedef char * pstr; 16 int mystr
 1 //相当于为现有类型创建一个别名,或称类型别名。
 2 //整形等
 3 typedef int size;
 4 
 5 
 6 //字符数组
 7 char line[81];
 8 char text[81];//=>
 9 
10 typedef char Line[81];
11 Line text, secondline;
12 
13 
14 //指针
15 typedef char * pstr;
16 int mystrcmp(pstr p1, pstr p2);//注:不能写成int mystrcmp(const pstr p1, const pstr p3);因const pstr p1解释为char * const cp(不是简单的替代)
17 
18 
19 //与结构类型组合使用
20 typedef struct tagMyStruct
21 {
22 int iNum;
23 long lLength;
24 } MyStruct;//(此处MyStruct为结构类型别名)=>
25 
26 struct tagMyStruct
27 {
28 int iNum;
29 long lLength;
30 };//+
31 typedef struct tagMyStruct MyStruct;
32 
33 
34 //结构中包含指向自己的指针用法
35 typedef struct tagNode
36 {
37 char *pItem;
38 pNode pNext;
39 } *pNode;//=>error
40 //1)
41 typedef struct tagNode
42 {
43 char *pItem;
44 struct tagNode *pNext;
45 } *pNode;
46 //2)
47 typedef struct tagNode *pNode;
48 struct tagNode
49 {
50 char *pItem;
51 pNode pNext;
52 };
53 //3)规范
54 struct tagNode
55 {
56 char *pItem;
57 struct tagNode *pNext;
58 };
59 typedef struct tagNode *pNode;
60 
61 
62 //与define的区别
63 //1)
64 typedef char* pStr1;//重新创建名字
65 #define pStr2 char *//简单文本替换
66 pStr1 s1, s2;
67 pStr2 s3, s4;=>pStr2 s3, *s4; 
68 //2)define定义时若定义中有表达式,加括号;typedef则无需。
69 #define f(x) x*x=>#define f(x) ((x)*(x))
70 main( )
71 {
72 int a=6,b=2,c;
73 c=f(a) / f(b);
74 printf("%d \\n",c);
75 }
76 //3)typedef不是简单的文本替换
77 typedef char * pStr;
78 char string[4] = "abc";
79 const char *p1 = string;
80 const pStr p2 = string;=>error
81 p1++;
82 p2++;
83 
84 //1) #define宏定义有一个特别的长处:可以使用 #ifdef ,#ifndef等来进行逻辑判断,还可以使用#undef来取消定义。
85 //2) typedef也有一个特别的长处:它符合范围规则,使用typedef定义的变量类型其作用范围限制在所定义的函数或者文件内(取决于此变量定义的位置),而宏定义则没有这种特性。

 1 //
 2 //C中定义结构类型
 3 typedef struct Student
 4 {
 5 int a;
 6 }Stu;//申明变量Stu stu1;或struct Student stu1;
 7 //
 8 typedef struct
 9 {
10 int a;
11 }Stu;//申明变量Stu stu1;
12 
13 //C++中定义结构类型
14 struct Student
15 {
16 int a;
17 };//申明变量Student stu2;
18 
19 
20 //C++中使用区别
21 struct Student 
22 { 
23 int a; 
24 }stu1;//stu1是一个变量 。访问stu1.a
25 
26 typedef struct Student2 
27 { 
28 int a; 
29 }stu2;//stu2是一个结构体类型 访问stu2 s2; s2.a=10;
30 //还有待增加。

 

转载于:https://www.cnblogs.com/diligentcalf/p/3558768.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/77870.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息