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

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

一、struct在C 中的使用

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

struct Student {
   int id;
   int name;
}stu1;
struct Student stu2;
stu1.id=1;
stu2.id=2;

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

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

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


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

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

所以有:

typedef struct Student {
    int id;
    string name;
}Student;
Student stu;
stu.id=1;
stu.name="zhangsan";
其中,typedef 给自定义类型struct Student 起了一个简单的别名:Student

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

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

typedef struct Student {
    int id;
    string name;
}Student1,Student2,Student3;
typedef定义了 3 个struct Student 类型的别名

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

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

typedef struct {
    int id;
    string name;
}Student1,Student2,Student3;


二、C++中的struct用法

1、

<pre name="code" class="cpp">struct Student {
    int id;
    string name;
}stu;
stu.id = 1;
stu.name="";


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

2、typedef

typedef struct Student {
    int id;
    string name;
}stu2;
stu2 s2;
s2.id=1;
s2.name="zhangsan";
上面 typedef 定义了一个结构体类型 stu2,所有要给id赋值,必须先定义一个结构体类型变量,如s2,然后才能s2.id =1;

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

struct Student {
   int id=1;
   string name;
}stu1,stu2,stu3;
定义了3个结构体变量 stu1,stu2,stu3

stu1.id =1;

stu2.id =2;

stu3.id =3;











發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章