对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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章