1. 程式人生 > >cpp小知識——struct和typedef struct

cpp小知識——struct和typedef struct

in C

  1. 使用typedef來定義一個結構體型別, 例如
typedef struct Student {
	int a;
}Stu;
  • 因為使用了typedef, 這裡的Stu, 其實就是struct Student的別名, 於是宣告變數的時候就可以Stu student1;

  • 假如沒有使用typedef, 那麼宣告變數的時候就需要struct Student student1;

  1. 另外, 也可以不寫Student, 例如
typedef struct {
	int a;
}Stu;

這樣, 宣告的時候必須是Stu student1;

in C++

  1. 可以直接定義結構體型別Student, 宣告變數的時候就可以直接Student student1了, 例如
struct Student {
	int a;
}
  1. 如果要使用typedef, 那麼會有這樣的區別
struct Student {
	int a;
}Stu1; 			// Stu1是一個變數
typedef struct Student {
	int a; 
}Stu2;			// Stu2是一個結構體型別

在使用時, 可以直接訪問Stu1.a

但是, 使用Stu2時, 需要先宣告一個變數, 然後再訪問其成員, 例如

Student student;
student.a = 2017;

其實可以這麼看, 在

typedef struct Student {
	int a; 
}Stu2;	

中, 其實是做了兩步工作的

  • 首先定義了一個結構體, 就是中間的部分, Student就是一個識別符號, 一個臨時名字
  • 其實typedef為這個結構起了一個新的名字, 叫Stu2, 所以就需要先宣告一個變數, 然後再訪問其成員變數