• 我们在哪一颗星上见过 ,以至如此相互思念 ;我们在哪一颗星上相互思念过,以至如此相互深爱
  • 我们在哪一颗星上分别 ,以至如此相互辉映 ;我们在哪一颗星上入睡 ,以至如此唤醒黎明
  • 认识世界 克服困难 洞悉所有 贴近生活 寻找珍爱 感受彼此

C++知识点:typedef

C++知识点 云涯 4年前 (2020-10-10) 1515次浏览

类型别名

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;
}

 

 

 


云涯历险记 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++知识点:typedef
喜欢 (0)