区别于 #define 文本替换,typedef 在编译期生效,属于类型系统一部分。
// 指针类型别名:同时声明多个指针变量
typedef char* PCHAR;
PCHAR pa, pb; // 两个 char* 指针
// 对比:char* pa, pb; // pb 是 char,非指针!
// 函数指针简化
typedef int (*CompareFunc)(const void*, const void*);
CompareFunc cmp = std::strcmp; // 代替 int (*cmp)(const void*, const void*) = std::strcmp;
// 数组指针简化
typedef double (*Matrix)[4]; // 指向 4 列 double 数组的指针
Matrix mat = new double[3][4];
// C 风格:必须带 struct 关键字
struct Point { int x, y; };
struct Point p1; // C 必须
// C++ 兼容写法:typedef 同时定义结构体与别名
typedef struct Point {
int x, y;
} Point; // 现在可直接 Point p1;
Point p2; // C++ 原生也支持,但 typedef 统一跨语言风格
// platform_types.h
#if defined(__LP64__) || defined(_WIN64)
typedef long int64_t;
typedef unsigned long uint64_t;
#else
typedef long long int64_t;
typedef unsigned long long uint64_t;
#endif
// 业务代码仅使用 int64_t,移植时只改此头文件
int64_t timestamp = getCurrentTime();
标准库广泛采用:size_t、ptrdiff_t、int32_t、uintptr_t 均为 typedef 产物。
// 标准库示例
typedef std::basic_string, std::allocator> string;
typedef std::basic_ofstream> ofstream;
// 自定义:回调函数类型
template <typename T>
using Callback = std::function<void(const T&)>; // C++11 using 更强,支持模板别名
typedef char* PSTR;
const PSTR p1 = "hello"; // 等价于 char* const p1(常量指针,指针不可改)
// 非 const char* p1(指向常量的指针)!
// 正确做法:在别名中包含 const
typedef const char* CSTR;
CSTR p2 = "world"; // 真正的 const char*
规则:const 修饰的是 typedef 定义的整个类型实体,而非底层基类型。
typedef static int MyInt; // 编译错误:multiple storage classes
typedef register int FastInt; // 同理错误
编译器将 typedef 视为 static/extern/auto 同级别的存储类说明符,同一声明中只能出现一个。
| 维度 | typedef | #define |
|---|---|---|
| 处理阶段 | 编译期(语义分析) | 预处理期(文本替换) |
| 作用域 | 遵循 C++ 作用域规则 | 全局文本替换,无作用域 |
| 指针声明 | typedef int* P; P a,b; 皆为指针 | #define P int* P a,b; b 为 int |
| const 语义 | 类型级约束 | 文本级展开,极易出错 |
| 调试可见性 | 调试器识别别名类型 | 调试器仅见展开后类型 |
| 模板别名 | C++11 using 支持 | 不支持 |
using 替代 typedef// 别名模板(typedef 无法做到)
template <typename T>
using Vec = std::vector<T, MyAllocator<T>>;
Vec<int> v; // 等价于 std::vector<int, MyAllocator<int>>
// 函数指针可读性更强
using Handler = std::function<void(int)>;
using Compare = bool(*)(int, int);
using 语法统一、支持模板、与 auto 风格一致,是 C++11 后的首选。