您的位置:首页 > 编程语言 > C语言/C++

C和C++中typedef struct的区别

2015-09-10 16:24 597 查看

1.C中typedef struct的用法

问题1:typedef是什么意思?

typedef 是C语言中专门为数据类型起别名的关键字

问题2:struct在C语言中如何使用?

例如定义一个student数据类型:

struct student{
int x;
int y;
};


此时用户声明该数据类型的对象时,必须这样:

struct student stu;


问题3:如何简化P2中的声明写法呢?

C语言的聪明者做了这样的修改:

typedef struct student{
int x;
int y;
}stu;
其表达含义是:stu和struct student是等价,是表示这种数据类型,此时可以:
stu s1;<div>struct student s2;</div>


可能读者会这样询问?能不能这样定义呢?typedef struct student{ int x; int y; };这种使用方法是错误的,想一想逻辑就可以了,发明typedef struct的人是想把C语言中结构体struct和typedef的有点结合在一块,而上述定义显然是只起到了结构的作用,并没有为struct student起别名的含义,故这种写法是不可取,因此没有存在的必要;
下面说一说这种修改的相当于:struct student{ int x; int y; };
typedef struct student stu;但是为什么不直接这样写呢?查阅前人资料,可能是因为这种做法多写了一个struct吧;

2.C++中typedef struct的阐述

问题1:typedef struct 和struct有区别吗?

两者是有区别的:

typedef struct student{ int x; int y; }stu;这种写法是和C语言中写法是一个意思,此处不加解释了;
struct student{
int x;
int y;
}stu;这种写法是区别于C语言中的,它表示新声明student数据类型,然后创建该类型的对象stu;
另外C语言中没有这种写法;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: