类型定义符 typedef

举报
用户已注销 发表于 2021/11/19 04:28:23 2021/11/19
【摘要】 目录 1,typedef——起别名 2,typedef 数组 3,typedef 和 结构体(数组) 4,typedef 和 宏 5,typedef 函数指针 1,typedef——起别名 typedef int INTEGER INTEGER a,b; 它等效于: int a,b; 2,typedef 数组 typ...

目录

1,typedef——起别名

2,typedef 数组

3,typedef 和 结构体(数组)

4,typedef 和 宏

5,typedef 函数指针


1,typedef——起别名

typedef int INTEGER
INTEGER a,b;
它等效于:
int a,b;

2,typedef 数组

typedef char NAME[20];
NAME a1,a2,s1,s2;
完全等效于:
char a1[20],a2[20],s1[20],s2[20]

3,typedef 和 结构体(数组)

示例:


  
  1. typedef struct struc
  2. {
  3. int a;
  4. int b;
  5. }stru,stru2[3];
  6. int main()
  7. {
  8. stru s1;
  9. stru2 s2;
  10. s1.a=1,s2[0].b=2;
  11. cout<<s1.a+s2[0].b;
  12. return 0;
  13. }

注意区分不用typedef的普通写法:


  
  1. struct struc
  2. {
  3. int a;
  4. int b;
  5. }stru,stru2[3];
  6. int main()
  7. {
  8. stru.a=1,stru2[0].b=2;
  9. cout<<stru.a+stru2[0].b;
  10. return 0;
  11. }

两个程序的逻辑一样,输出结果都是3

4,typedef 和 宏

有时也可用宏定义来代替 typedef 的功能:

typedef 原类型名 新类型名

#define 新类型名 原类型名

但是宏定义是由预处理完成的,而 typedef则是在编译时完成的,而且typedef的带数组的用法是不能用宏替代的。

5,typedef 函数指针

示例:


  
  1. typedef char (*func)(int);
  2. char GetChar(int a)
  3. {
  4. return '0' + a%10;
  5. }
  6. int main()
  7. {
  8. func f=GetChar;
  9. cout<<f(5);
  10. return 0;
  11. }

输出:

5

文章来源: blog.csdn.net,作者:csuzhucong,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/nameofcsdn/article/details/103936770

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。