本帖最后由 人造人 于 2019-6-3 23:12 编辑
在C++中
- struct EleType
- {
- int id;
- char name[64];
- };
- EleType e1;
- struct EleType e2;
复制代码
EleType e1;
struct EleType e2;
加struct和不加完全一样,书上好像就是这么写的
struct后面的名字在全局空间
在C语言中
- struct EleType
- {
- int id;
- char name[64];
- };
- EleType e1;
- struct EleType e2;
复制代码
EleType e1;报错,说找不到这个名字
C语言中的struct后面这个名字不在全局空间,你用的时候每次都要加上struct,很麻烦,解决方法是用typedef把这个名字放到全局空间
例如这样就可以了
- typedef struct EleType
- {
- int id;
- char name[64];
- } Eletype;
- EleType e1;
- struct EleType e2;
复制代码
但是在C++中名字本来就在全局空间,你用typedef反而导致了名字冲突
也就是说,理论上改成这样就行了
- #ifndef staticlinklist_h_include
- #define staticlinklist_h_include
- /*
- 静态链表 SLL
- */
- #include<iostream>
- using namespace std;
- #define MAX_SIZE_SSL 10
- typedef struct {
- int id;
- string name;
- }EleType;
- //静态链表,就是一个结构数组
- //typedef struct Slist{
- typedef struct {
- EleType data;
- int next; //游标cursor,若果为零表示无指向
- }Slist[MAX_SIZE_SSL];
- void InitSLL(Slist sList);//初始化
- void PrintSLL(Slist sList);//打印
- #endif
复制代码
但是,C/C++中的这个typedef真的就是一个别名,你这样改编译器会说
- ‘void InitSLL(<unnamed struct>*)’, declared using unnamed type, is used but never defined
复制代码
编译器会说Slist sList的类型是<unnamed struct>*
C/C++中的这个typedef真的就是一个别名
那么好吧,这样总行了吧,你别说这样一改还真行了^_^
- #ifndef staticlinklist_h_include
- #define staticlinklist_h_include
- /*
- 静态链表 SLL
- */
- #include<iostream>
- using namespace std;
- #define MAX_SIZE_SSL 10
- typedef struct {
- int id;
- string name;
- }EleType;
- //静态链表,就是一个结构数组
- //typedef struct Slist{
- typedef struct Slist_tag{
- EleType data;
- int next; //游标cursor,若果为零表示无指向
- }Slist[MAX_SIZE_SSL];
- void InitSLL(Slist sList);//初始化
- void PrintSLL(Slist sList);//打印
- #endif
复制代码
也就是保证struct后面的名字和typedef生成的名字不一样,因为这两个名字都在全局空间,名字一样会导致冲突
- //静态链表,就是一个结构数组
- //typedef struct Slist{
- typedef struct Slist_tag{
- EleType data;
- int next; //游标cursor,若果为零表示无指向
- }Slist[MAX_SIZE_SSL];
复制代码