在 C++ 中,关键字(Keywords) 是语言预定义的保留字,具有特殊含义,不能用作标识符(如变量名、函数名等)。
核心关键字分类
1. 基本类型
int,char,bool,float,double,voidshort,long,signed,unsignedauto(自动类型推导)
2. 类型修饰符
const(常量)volatile(防止编译器优化)mutable(允许在const成员函数中修改)
3. 复合类型
struct,class,union,enumusing(类型别名或引入命名空间)typedef(类型别名,C++11 后推荐用using)
4. 存储类别
static(静态存储期)extern(外部链接)register(建议寄存器存储,已弃用)thread_local(线程局部存储)
5. 函数相关
virtual(虚函数)override(显式重写虚函数)final(禁止重写/继承)explicit(禁止隐式转换)inline(内联函数)friend(友元)
6. 控制流
if,else,switch,case,defaultfor,while,do,break,continuegoto,return
7. 异常处理
try,catch,throw,noexcept
8. 动态内存
new,delete,new[],delete[]
9. 模板编程
template,typenamerequires(C++20 概念约束)
10. 命名空间
- `namespace`, `using namespace`
11. 类型转换
- `static_cast`, `dynamic_cast`, `const_cast`, `reinterpret_cast`
- `typeid`(获取类型信息)
12. 其他重要关键字
- `this`(当前对象指针)
- `nullptr`(空指针)
- `sizeof`(类型/对象大小)
- `operator`(重载运算符)
- `asm`(内联汇编)
C++11/14/17/20 新增关键字
| 关键字 | 用途 | 标准版本 |
|---|---|---|
constexpr | 编译时常量/函数 | C++11 |
decltype | 推导表达式类型 | C++11 |
noexcept | 声明函数不抛出异常 | C++11 |
nullptr | 类型安全的空指针 | C++11 |
alignas | 指定对齐方式 | C++11 |
alignof | 获取对齐要求 | C++11 |
thread_local | 线程局部存储 | C++11 |
char16_t | UTF-16 字符类型 | C++11 |
char32_t | UTF-32 字符类型 | C++11 |
consteval | 立即函数(编译时执行) | C++20 |
concept | 模板约束(概念) | C++20 |
requires | 概念约束的子句 | C++20 |
co_await | 协程等待 | C++20 |
co_yield | 协程返回值 | C++20 |
co_return | 协程返回 | C++20 |
禁止用作标识符的示例
int class = 10; // 错误:'class' 是关键字
void delete() {} // 错误:'delete' 是关键字
完整关键字列表(按字母顺序)
alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break,
case, catch, char, char8_t, char16_t, char32_t, class, compl, concept,
const, constexpr, const_cast, continue, co_await, co_return, co_yield,
decltype, default, delete, do, double, dynamic_cast, else, enum, explicit,
export, extern, false, float, for, friend, goto, if, inline, int, long,
mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or,
or_eq, private, protected, public, register, reinterpret_cast, requires,
return, short, signed, sizeof, static, static_assert, static_cast, struct,
switch, template, this, thread_local, throw, true, try, typedef, typeid,
typename, union, unsigned, using, virtual, void, volatile, wchar_t, while,
xor, xor_eq
关键注意事项
- 与 C 的差异:
C++ 新增了class,namespace,dynamic_cast等关键字,而 C 的关键字如_Bool,_Complex不在 C++ 中。 - 替代运算符:
and(代替&&)、or(代替||)、not(代替!)等是标准关键字。 - 弃用关键字:
register在 C++17 后被弃用(但仍是关键字)。
1万+

被折叠的 条评论
为什么被折叠?



