本文最后更新于 2025年7月19日 上午
C++的一些关键字
在C++中关键字会随着C++版本更新而新加,所以后续如果有新推出再补充。
常见的关键字
auto
- 在声明变量时,使用
auto关键字,编译器会根据变量的初始化表达式自动推断出该变量的类型。
1 2 3
| auto a = 10; auto b = 3.14; auto c = true;
|
break
- 跳出循环(
for、while、do - while)或 switch 语句。
1 2 3 4 5 6 7 8 9 10
| int a = 1; while(true) { if(a>2) { break; } cout<<1<<endl; a++; }
|
case
1 2 3 4 5 6 7 8 9 10 11
| switch (expression) { case constant1: break; case constant2: break; ... default: }
|
catch
1 2 3 4 5 6 7 8 9
| try { } catch (ExceptionType1 e1) { } catch (ExceptionType2 e2) { } catch (...) { }
|
class
1 2 3 4 5 6 7 8 9 10 11 12 13
| class ClassName { access-specifier1: datatype member1; return_type function1();
access-specifier2: datatype member2; return_type function2(); ... };
|
const
const 声明常量,修饰的变量值不能被改变,也可以修饰成员函数,表示该函数不会修改对象的数据成员。
1 2 3 4 5 6
| const int x = 10; const double pi = 3.14159; const char str = "Hello, world!"; const int* ptr1 = &x; int* const ptr2 = &y; const int* const ptr = &x;
|
constexpr (C++11)
- 声明可在编译时求值的常量表达式
1 2 3 4
| constexpr int square(int n) { return n * n; } constexpr int val = square(10);
|
continue
- 跳过当前循环迭代,进入下一次循环
1 2 3 4
| for(int i=0; i<10; i++) { if(i%2 == 0) continue; cout << i << endl; }
|
default
- 在
switch语句中指定默认分支
- 显式生成默认构造函数/析构函数
1 2 3 4 5 6 7 8 9
| class MyClass { public: MyClass() = default; };
switch(code) { case 200: break; default: ; }
|
delete
- 释放new分配的内存
- 显式删除函数(C++11)
1 2 3 4
| int* ptr = new int[10]; delete[] ptr;
void func(int) = delete;
|
do
do-while循环的起始标记1 2 3 4
| int i = 0; do { cout << i++; } while(i < 5);
|
double
- 声明双精度浮点类型(通常8字节)
1 2 3 4
| double pi = 3.1415926535; double calculateArea(double r) { return pi * r * r; }
|
else
if语句的备用分支1 2 3 4 5 6 7
| if(temperature > 30) { cout << "Hot"; } else if(temperature > 20) { cout << "Warm"; } else { cout << "Cool"; }
|
enum
- 声明枚举类型
1 2 3 4 5
| enum Color { RED, GREEN, BLUE }; Color c = GREEN;
enum class FileMode { Read, Write, Append };
|
explicit
- 禁止构造函数隐式转换
1 2 3 4 5 6 7
| class MyString { public: explicit MyString(int size) { } };
MyString s(10);
|
extern
- 声明外部链接(变量/函数在其他文件定义)
1 2 3 4 5
| extern int globalVar;
extern void helper();
|
false
- 布尔类型的假值
1 2 3 4
| bool isValid = false; if(!isValid) { cerr << "Invalid operation"; }
|
float
- 声明单精度浮点类型(通常4字节)
1 2 3 4
| float gravity = 9.8f; float calculateForce(float mass) { return mass * gravity; }
|
for
- 循环控制结构
1 2 3 4 5 6
| for(int i=0; i<10; i++) { }
vector<int> nums {1,2,3}; for(auto n : nums) { }
|
friend
- 允许非成员函数/其他类访问私有成员
1 2 3 4 5 6 7 8 9
| class Box { double width; friend void printWidth(Box box); friend class BoxFactory; };
void printWidth(Box box) { cout << box.width; }
|
goto (慎用)
- 无条件跳转语句
1 2 3 4 5 6 7
| for(...) { for(...) { if(error) goto cleanup; } } cleanup:
|
if
- 条件判断语句
1 2 3
| if(ptr != nullptr) { }
|
inline
- 建议编译器内联展开函数
- 头文件中定义成员函数
1 2 3
| inline int max(int a, int b) { return a > b ? a : b; }
|
int
- 声明整型变量(通常4字节)
1 2 3 4
| int count = 0; int add(int a, int b) { return a + b; }
|
long
- 长整型修饰符
1 2
| long bigValue = 1000000L; long double highPrecision = 3.141592653589793238L;
|
mutable
- 允许const成员函数修改的成员
1 2 3 4 5 6 7
| class Cache { mutable bool dirty {false}; public: void update() const { dirty = true; } };
|
namespace
- 定义命名空间(避免命名冲突)
1 2 3 4 5 6
| namespace MyLib { class File { }; void open(File& f); }
using MyLib::File;
|
new
- 动态内存分配
1 2 3 4 5
| int* ptr = new int(100); int* arr = new int[10];
auto uptr = std::make_unique<MyClass>();
|
operator
- 运算符重载
1 2 3 4 5 6
| class Vector { public: Vector operator+(const Vector& other) { } };
|
private
- 类私有成员访问控制
1 2 3 4 5 6
| class Account { private: double balance; public: void deposit(double amt) { balance += amt; } };
|
protected
- 类保护成员访问控制
1 2 3 4
| class Base { protected: int protectedVar; };
|
public
- 类公有成员访问控制
1 2 3 4 5
| class User { public: string name; void login() { } };
|
return
- 从函数返回值
1 2 3 4
| int factorial(int n) { if(n <= 1) return 1; return n * factorial(n-1); }
|
short
signed
- 有符号类型修饰符
1
| signed char temperature = -5;
|
sizeof
- 获取类型/对象的内存大小
1 2 3 4 5
| cout << sizeof(int); cout << sizeof(double);
int arr[10]; cout << sizeof(arr);
|
static
- 静态局部变量(保持状态)
- 类静态成员(共享数据)
- 文件作用域(内部链接)
1 2 3 4 5 6 7 8
| void counter() { static int count = 0; cout << ++count; }
class MyClass { static int instanceCount; };
|
struct
- 声明结构体(默认公有访问)
1 2 3 4 5
| struct Point { int x, y; };
|
switch
- 多分支选择语句
1 2 3 4 5
| switch(deviceStatus) { case Status::Offline: break; case Status::Online: break; default: ; }
|
template
- 泛型编程
1 2 3 4 5 6 7
| template <typename T> T max(T a, T b) { return a > b ? a : b; }
cout << max(10, 20); cout << max(3.14, 2.99);
|
this
- 指向当前对象的指针
1 2 3 4 5 6 7
| class MyClass { int val; public: void setVal(int val) { this->val = val; } };
|
throw
- 抛出异常
1 2 3 4
| void processFile(const string& path) { if(!fileExists(path)) throw runtime_error("File not found"); }
|
true
- 布尔类型的真值
1 2 3 4
| bool isReady = true; if(isReady) { launchOperation(); }
|
try
- 异常处理代码块
1 2 3 4 5
| try { riskyOperation(); } catch(const exception& e) { cerr << "Error: " << e.what(); }
|
typedef
- 创建类型别名
1 2 3 4 5
| typedef vector<string> StringList; StringList names;
using StringList = vector<string>;
|
typename
- 模板中声明类型参数
- 指示依赖类型名称
1 2 3 4
| template <typename T> class Container { typename T::iterator it; };
|
unsigned
- 无符号类型修饰符
1
| unsigned int positiveOnly = 42;
|
virtual
- 声明虚函数(支持多态)
1 2 3 4 5 6 7 8
| class Shape { public: virtual void draw() const = 0; };
class Circle : public Shape { void draw() const override { } };
|
void
- 无返回值函数
- 通用指针类型
1 2 3
| void logMessage(string msg);
void* ptr = malloc(100);
|
volatile
- 防止编译器优化(用于硬件寄存器等)
1 2
| volatile bool interruptFlag = false;
|
while
- 循环控制结构
1 2 3 4
| while(!queue.empty()) { process(queue.front()); queue.pop(); }
|
现代C++新增关键字
nullptr (C++11)
- 类型安全的空指针常量
1 2
| int* ptr = nullptr; if(ptr == nullptr) { }
|
noexcept (C++11)
- 声明函数不抛出异常
1 2 3
| void safeFunction() noexcept { }
|
override (C++11)
- 显式标记重写虚函数
1 2 3
| class Derived : public Base { void func() override; };
|
final (C++11)
- 禁止类被继承
- 禁止虚函数被重写
1 2 3 4 5
| class Base final { };
class Derived : public Base { virtual void foo() final; };
|
decltype (C++11)
- 推导表达式类型
1 2 3 4 5
| int x = 10; decltype(x) y = 20;
template <typename T, typename U> auto add(T t, U u) -> decltype(t+u) { return t+u; }
|
thread_local (C++11)
- 线程局部存储
1
| thread_local int counter = 0;
|
consteval (C++20)
- 立即函数(必须在编译时执行)
1 2 3 4
| consteval int square(int n) { return n*n; } constexpr int val = square(10);
|