對typedef關鍵字的理解

1. 不要將typedef理解成type define ,可以理解爲typerename或其他:

typeddef是給一個已經存在數據類型取一個別名,並非定義一個新的數據類型(有重命名的意思 rename)

目的是使這個數據類型的新名字更能合適的表達出想要表達的意思

例題:

typedef struct student
{
	//code
} Stu_st,*Stu_pst;

把 struct student
{
	//code
} 
看作一個整體,typedef給struct student{  //code   }  取了個別名叫  Stu_st                     
                     給struct student{  //code   }* 這個結構體指針 取了個別名叫  Stu_pst
也就是Stu_pst是一個結構體指針的別名
Stu_st是一個結構體的別名
A:  struct student stu1;  <=>    Stu_st  stu1;       //用結構體類型的不同別名定義一個結構體stu1                

B:  struct student *stu2;  <=>     Stu_st *stu2; <=>  Stu_pst stu2;       //定義一個結構體指針 stu2 

(Stu_pst本身就是一個結構體指針,不加* )


2.

#include <stdio.h>

typedef int  int32;
#define INT32 int

void main(void)
{
    unsigned int32 i = 10;
    unsigned INT32 j = 10;
}
error C2146: syntax error : missing ';' before identifier 'i'

error C2065: 'i' : undeclared identifier

原因:#define宏定義在預編譯時會把INT32替換成int

而typedef 別名不支持這種擴展

typedef static int  int32;

Vs2010  C++編譯器會報錯:error C2159: more than one storage class specified  

typedef和auto、static、register一樣是存儲類關鍵字,在定義別名時不能在出現存儲類的關鍵字,所以不行

3. typedef和const放在一起
C: const Stu_pst stu3;

D: Stu_pst const stu4;

C,D中的const分別修飾誰?

const修飾誰都可以將數據類型名忽略,看離它最近的是誰就是修飾誰

C: Stu_pst是“struct student{ }*”的別名,“struct student{ }*”是一個整體,對於編譯器來說,只認爲Stu_pst是一個類型名,所以解析的時候直接把它忽略掉,即constStu_pst stu3; 則const修飾stu3結構體指針本身,而不是它指向的對象

D:Stu_pstconst stu4;  顯然,const修飾stu4結構體指針


發佈了34 篇原創文章 · 獲贊 19 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章