【C++】struct与typedef struct

1. c

typedef的作用

typedef可以声明新的类型名来代替已有的类型名,但却不能增加新的类型。
  
typedef为C语言的关键字,作用是为一种数据类型定义一个新名字。这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)。
  
在编程中使用typedef目的一般有两个,一个是给变量提供一个易记且意义明确的新名字(类型有新别名,方便变量的定义),另一个是简化一些比较复杂的类型声明。

struct 与 typedef struct 的区别

typedef是类型定义的意思。
typedef struct 是为了使用这个结构体方便。

具体区别在于:
若这样来定义结构体的话

struct student  // 结构体名是 student
 {    
     int a,    
 };

在声明student 的变量时,需要这样写

struct student stu1; // 必须要写struct,这样每次声明变量都需要写struct,很麻烦

若用typedef来定义结构体的话

typedef struct student 
{
    int a,
}Stu;   // 将 struct student 重新命名为 Stu

在声明变量时就可以这样写

Stu stu1;

区别就在于使用时,是否可以省去struct这个关键字。

标准形式

先定义后声明

//定义结构体
struct teacher{
    char name[20];
    int age;
    char email[50];
};
//声明结构体变量
struct teacher teacher1;

定义的同时进行声明

//定义时声明变量
struct teacher{
    char name[20];
    int age;
    char email[50];
}teacher1, teacher2;

使用typedef定义结构体

//定义结构体
typedef struct Student
{
    char name[50];
    int age;
}Stu;
//声明结构体变量
Stu stu1;

直接(不使用Student)

//定义结构体
typedef struct
{
    int a;
}Stu;
//声明结构体变量
Stu stu1;

2. c++

其次:在c++中如果用typedef的话,又会造成区别:

struct Student
{
    int a;
}stu1;//stu1是一个变量
typedef struct Student2
{
    int a;
}stu2;//stu2是一个结构体类型
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值