typedef关键字、using关键字
目录
1. typedef 的基本用法
2. typedef 与指针
3. typedef 与结构体
4. C++11 引入 using 作为 typedef 的替代
5. typedef 在模板中的限制
总结
typedef为某类型定义一个别名。当关键字typedef作为声明的基本类型出现时,声明中定义的名字就是类型名。
在 C++11 及更早的标准中,typedef
关键字用于为已有类型定义别名。尽管 C++11 引入了 using
关键字作为更现代的类型别名定义方式,但 typedef
仍然有效。
1. typedef
的基本用法
#include <iostream>
// 定义类型别名
typedef unsigned int uint;
int main() {
uint x = 42; // uint 实际上是 unsigned int
std::cout << x << std::endl;
return 0;
}
✅ 解析:
typedef unsigned int uint;
定义了uint
作为unsigned int
的别名。- 之后可以用
uint
代替unsigned int
声明变量。
2. typedef
与指针
#include <iostream>
typedef int* IntPtr; // IntPtr 现在是 int* 的别名
int main() {
int a = 10, b = 20;
IntPtr p1 = &a, p2 = &b; // 等价于 int* p1, p2;
std::cout << *p1 << ", " << *p2 << std::endl;
return 0;
}
✅ 注意:
IntPtr p1, p2;
实际上等价于:int* p1, p2; // p1 是指针,p2 是 int(⚠️ 容易误解)
- 所以
typedef
定义指针类型时,建议每个变量单独声明。
3. typedef
与结构体
在 C 语言中,定义结构体时通常会使用 typedef
:
#include <iostream>
typedef struct {
int x;
int y;
} Point; // Point 现在是 struct 的别名
int main() {
Point p = {10, 20}; // 直接使用别名定义结构体变量
std::cout << p.x << ", " << p.y << std::endl;
return 0;
}
✅ 解析:
typedef struct {...} Point;
让Point
作为结构体的类型别名,不必写struct Point
。
4. C++11 引入 using
作为 typedef
的替代
C++11 引入 using
关键字,可以更简洁地定义类型别名:
using uint = unsigned int; // 等价于 typedef unsigned int uint;
using IntPtr = int*; // 等价于 typedef int* IntPtr;
uint num = 42;
IntPtr ptr = #
✅ 推荐使用 using
,因为:
using
更符合现代 C++ 语法,可读性更好。using
支持模板别名(typedef
不支持)。
5. typedef
在模板中的限制
typedef
不能 直接用于模板别名,而 using
可以:
// ❌ 错误:typedef 不能用于模板别名
template <typename T>
typedef std::vector<T> Vec;
// ✅ 正确:using 可以用于模板别名
template <typename T>
using Vec = std::vector<T>;
Vec<int> v = {1, 2, 3}; // 等价于 std::vector<int> v
总结
特性 | typedef | using (C++11) |
---|---|---|
基本类型别名 | ✅ | ✅ |
指针类型别名 | ✅ | ✅ |
结构体别名 | ✅ | ✅ |
模板别名 | ❌ 不支持 | ✅ 支持 |
推荐使用 | ❌(已被 using 替代) | ✅(C++11 及以后) |
🚀 现代 C++ 推荐使用 using
,因为它更简洁、支持模板,并且可读性更强!