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的一个keyword,在C 和C++ 中都是给一个数据类型定义一个新的名字。这里的数据类型包含基本数据类型(int, char等)和自己定义的数据类型(struct)。

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

所以有:

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;











原文地址:https://www.cnblogs.com/yxysuanfa/p/7136375.html