类型别名
1. 定义类型别名
int main() { char *pa,pb;//声明了一个指向字符变量的指针pa,和一个字符变量pb pa = "hello"; pb = "hello";//报错,不能将const char*类型的值赋给char类型的实体 pb = 'h';//正常 return 0; }
int main() { typedef char* PCHAR; PCHAR pa,pb; pa = "hello"; pb = "hello";//正常 pb = 'h';//报错,不能将char类型的值赋给PCHAR类型实体 return 0; }
注意事项
p1和p2都是常量指针,意思是指针指向的内容不能修改,而指针是可以修改的。
那为什么p1++正常,而p2++报错呢。
对于p1++,我们不用再解释了,因为常量指针是可变的。
而p2是我们定义的别名,而不是系统固有类型,编译器在编译时,会认为p2是常量,不可修改,
所以p2++会报错。
typedef char* pStr;
const char* p1 = "hello";
const pStr p2 = "hello";
p1++;//正常
p2++;//报错
2. 定义struct结构体别名
struct tagPOINT1 { int x; int y; }; struct tagPOINT1 p1; //当声明一个结构体对象时,必须要带上struct
typedef struct tagPOINT1 { int x; int y; }POINT; POINT p1; //当我们用typedef定义struct的别名后,可以直接用别名 对象名来声明一个对象
3. 为复杂的声明定义一个简单别名
typedef int (*A) (char, char);
A 是定义的别名,表示一个指向函数的指针
该函数有两个char类型参数,返回int值
#include<iostream> using namespace std; typedef int (*A)(char,char); int fun0(char a,char b); int fun1(char a,char b); int main() { A a; a = fun0; a('a','b'); a = fun1; a('a','b'); return 0; } int fun0(char a,char b) { cout<<"fun0"<<endl; return 0; } int fun1(char a,char b) { cout<<"fun1"<<endl; return 0; }