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;











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