目录
一、为基本数据类型定义新的类型名
此声明定义了一个 int 的同义字,名字为 size。注意 typedef 并不创建新的类型。它仅仅为现有类型添加一个同义字
#include <iostream>
using namespace std;
typedef long long LL; //一般像宏一样大写
int main() {
// your code goes here
ll x=100;
return 0;
}
尤其在指针定义时非常有用
//简化写法,有效地避免了char *a,b的错误
char *a,*b;
//使用typedef
typedef char* PCHAR;
PCHAR a,b;
二、为C语言简写struct
为C语言简写struct:以前的代码中,声明struct新对象时,必须要带上struct,即形式为: struct 结构名 对象名,如:
//定义stu结构体类型
struct stud
{
int x;
int y;
};
//定义一个stu结构体类型的变量,名为student1
struct stu student1;
typedef struct stu
{
int x;
int y;
}stu;
stu student;
在C++中,则可以直接写:结构名 对象名,即:
struct stu
{
int x;
int y;
};
stu student;
三、简写数组名
格式:typedef T T别名 [N]
注意:[ ]写在最后
//为数组定义简洁的类型名称
#include<iostream>
using namespace std;
typedef int INT_100[100];
int main()
{
INT_100 arr;
arr[0]=100;
cout<<arr[0];
//100
return 0;
}
四、陷阱
1.常量指针与指针常量
typedef不像宏一样是简单的字符串替换,而是定义了一种类型的新别名
typedef int* PINT;
int x=110,y=120;
const PINT p=&x;
*p=120; //ok
p=&y; //error
//p指针指向的对象的值可以被修改,而指针的指向不可以被修改
//说明这是指针常量,而我们想定义的是常量指针。
“const PINT”中的 const 给予了整个指针本身常量性,也就是形成了指针常量“int* const”,而不是我们想要的常量指针“const int*”。这类似于const int a=10,a=100出错,说明10和100都是常量,而a不能指向100说明a的指向不能发生变化,所以const PINT形成了指针常量。
当然,要想让 const pint 相当于 const int* 也很容易,如下面的代码所示:
typerdef const int* CPINT;
int x=120,y=911;
CPINT p=&x;
p=&y; //ok
*p=315; //error
//指针指向的值不能发生变化,指针的指向可以发生变化
//说明是常量指针
2.冲突的说明符
typedef在语法上是一个存储类的关键字(如auto、extern、mutable、static、register等一样),虽然它并不真正影响对象的存储特性,如:
typedef static int STATIC_INT;
//[Error] conflicting specifiers in declaration of 'STATIC_INT'
编译将失败,会提示“指定了一个以上的存储类”。