在C语言中的应用
定义类型的别名
typedef int ElemType;
ElemType a;//此处的ElemType a就等价于int a
当然上述的作用这么看来可能没什么必要,但有时还是可以增加代码的美观度和整齐性的。如当我们定义指针变量时:
int *a,*b;
这几个指针变量都带着*有时是不是看着挺烦的。在这可以用typedef来定义个指针类型的别名,使他看起来舒服些。
typedef int* PINT;
PINT a,b;
这样的声明和上面的效果一样,看起来舒服些(强迫症患者)
这样看来好像没啥大用,但在辅助struct时可以简化代码。
struct animal{
char a
};
struct animal dog;
typedef struct animal{
char a;
}ani;
ani dog;
可以看出在以后每次声明机构体变量时可以少写一个struct。这里实质上也是别名作用。有没有感觉
typedef struct animal {char a;} ani;
和
typedef int ElemType;
很相似。
这里还可以进一步简化省掉struct(但声明时也不可以使用animal dog了,只能用ani dog)
typedef struct{
char a;
}ani;
ani dog;
有时为了区分同一变量在不同地方的不同含义可能有多个别名
typedef struct animal{
char a;
}a,b,c;//这里的a,b,c都是别名,作用相同
在C++语言中的应用
struct Animal{
char a;
};
Animal dog;
直接定义机构体声明直接Animal dog就可以了当然也可以定义声明一气呵成
struct Animal{
char a;
}dog;
这样看可能不是很清楚,把它拉直看
struct Animal {char a;} dog;// struct Animal {char a;}为定义部分
同时建立了一个对象dog。
注意:因为c++比c多出了对象的概念,与c的用法不同。
typedef struct Animal{
char a;
}ani;
ani dog;
当使用typedef struct 时后面的ani就不是对象了而是结构体的别名,想要建立对象就要再次声明。