struct结构体在c和c++中的区别

很多次遇到这个struct的问题,今天在这里简单总结一下我的理解

一、struct在C 中的使用

1、单独使用struct定义结构体类型

[cpp]  view plain  copy
  1. struct Student {  
  2.    int id;  
  3.    int name;  
  4. }stu1;  
  5. struct Student stu2;  
  6. stu1.id=1;  
  7. stu2.id=2;  

上面定义了一个结构体类型struct Student 和一个结构体类型变量stu1。

所以有两种定义结构体变量的方式:

一种是这就跟在结构体定义的后面(}之后),一种是用 struct  结构体名  结构体变量名。


2、typedef:typedef作为C的一个关键字,在C 和C++ 中都是给一个数据类型定义一个新的名字。这里的数据类型包括基本数据类型(int, char等)和自定义的数据类型(struct)。

编程中使用typedef,其目的一般有两个,一个是给变量一个容易记且意义明确的新名字,另一个是简化一些比较复杂的类型声明。

所以有:

[cpp]  view plain  copy
  1. typedef struct Student {  
  2.     int id;  
  3.     string name;  
  4. }Student;  
  5. Student stu;  
  6. stu.id=1;  
  7. stu.name="zhangsan";  
其中,typedef 给自定义类型struct Student 起了一个简单的别名:Student

所以Student stu; 就等价于1中的struct Student stu;

3、typedef 定义批量的类型别名

[cpp]  view plain  copy
  1. typedef struct Student {  
  2.     int id;  
  3.     string name;  
  4. }Student1,Student2,Student3;  
typedef定义了 3 个struct Student 类型的别名

但是如果去掉了typedef,那么在C++中,Student1,Student2,Student3将是3个结构体变量

当然,如果,Student 以后用不着,则可以省略Student,如下所示功能与3相同。

[cpp]  view plain  copy
  1. typedef struct {  
  2.     int id;  
  3.     string name;  
  4. }Student1,Student2,Student3;  


二、C++中的struct用法

1、

[cpp]  view plain  copy
  1. <pre name="code" class="cpp">struct Student {  
  2.     int id;  
  3.     string name;  
  4. }stu;  
  5. stu.id = 1;  
  6. stu.name="";  

 定义了一个Student类型的结构体,还声明了Student类型的一个结构体变量stu。 
 

2、typedef

[cpp]  view plain  copy
  1. typedef struct Student {  
  2.     int id;  
  3.     string name;  
  4. }stu2;  
  5. stu2 s2;  
  6. s2.id=1;  
  7. s2.name="zhangsan";  
上面 typedef 定义了一个结构体类型 stu2,所有要给id赋值,必须先定义一个结构体类型变量,如s2,然后才能s2.id =1;

3、struct 定义批量的结构体变量

[cpp]  view plain  copy
  1. struct Student {  
  2.    int id=1;  
  3.    string name;  
  4. }stu1,stu2,stu3;  
定义了3个结构体变量  stu1,stu2,stu3

stu1.id =1;

stu2.id =2;

stu3.id =3;








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值