Typedef 的基本语法
typedef 的基本语法格式如下:
typedef existing_type new_type_name;
existing_type 是已经存在的数据类型,new_type_name 是为该类型定义的新名称。
示例:
typedef unsigned int uint;
uint a = 10; // 等同于 unsigned int a = 10;
为基本类型创建别名
typedef 常用于为基本数据类型创建更简洁或更有意义的别名。
typedef char byte;
typedef int bool;
typedef float real;
byte b = 'A';
bool flag = 1;
real pi = 3.14159;
为结构体创建别名
typedef 可以简化结构体的声明和使用。
// 未使用typedef
struct Point {
int x;
int y;
};
struct Point p1;
// 使用typedef
typedef struct {
int x;
int y;
} Point;
Point p2;
为指针类型创建别名
typedef 可以简化指针类型的声明。
typedef char* String;
String s = "Hello";
typedef int* IntPtr;
IntPtr p = (int*)malloc(sizeof(int)*10);
为函数指针创建别名
typedef 特别适合简化复杂的函数指针声明。
typedef int (*CompareFunc)(const void*, const void*);
int compare_ints(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
CompareFunc cmp = compare_ints;
int arr[] = {5, 2, 8, 1};
qsort(arr, 4, sizeof(int), cmp);
为数组类型创建别名
typedef 可以为数组类型创建别名,特别是多维数组。
typedef int Vector3[3];
typedef float Matrix4x4[4][4];
Vector3 v = {1, 2, 3};
Matrix4x4 m = {
{1.0f, 0.0f, 0.0f, 0.0f},
{0.0f, 1.0f, 0.0f, 0.0f},
{0.0f, 0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 0.0f, 1.0f}
};
为复杂类型创建多层别名
typedef 可以嵌套使用,为复杂类型创建多层别名。
typedef int* IntPtr;
typedef IntPtr* IntPtrPtr;
int x = 10;
IntPtr p = &x;
IntPtrPtr pp = &p;
平台无关的类型定义
typedef 常用于创建平台无关的类型定义,提高代码可移植性。
#ifdef _WIN32
typedef __int64 int64_t;
#else
typedef long long int64_t;
#endif
int64_t big_num = 9223372036854775807LL;
类型安全
typedef 可以增强类型安全性,防止误用。
typedef int Meters;
typedef int Kilograms;
Meters length = 10;
Kilograms weight = 70;
// length = weight; // 虽然语法允许,但逻辑错误明显
与宏定义的区别
typedef 与 #define 有重要区别:typedef 是类型定义,#define 是文本替换。
#define PINT int*
typedef int* intPtr;
PINT a, b; // a是int*,b是int
intPtr c, d; // c和d都是int*
在C++中的使用
在C++中,typedef 可以用 using 替代,但 typedef 仍然被广泛支持。
typedef std::vector<std::string> StringVector;
// C++11 equivalent
using StringVector = std::vector<std::string>;
实际应用案例
以下是一个综合应用示例,展示typedef在实际项目中的使用:
typedef struct {
int id;
char name[50];
} Employee;
typedef Employee* EmployeePtr;
typedef void (*PrintFunc)(EmployeePtr);
void printEmployee(EmployeePtr emp) {
printf("ID: %d, Name: %s\n", emp->id, emp->name);
}
int main() {
Employee e = {101, "John Doe"};
EmployeePtr ep = &e;
PrintFunc pf = printEmployee;
pf(ep);
return 0;
}