C++的一些关键字

本文最后更新于 2025年7月19日 上午

C++的一些关键字

在C++中关键字会随着C++版本更新而新加,所以后续如果有新推出再补充。

常见的关键字

auto

  • 在声明变量时,使用auto关键字,编译器会根据变量的初始化表达式自动推断出该变量的类型。
1
2
3
auto a = 10; // 自动声明为int类型
auto b = 3.14; // 自动声明为double类型
auto c = true; //自动声明为bool类型

break

  • 跳出循环(forwhiledo - 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

  • 用于 switch 语句中的分支情况
1
2
3
4
5
6
7
8
9
10
11
switch (expression) {
case constant1:
// 代码块1
break;
case constant2:
// 代码块2
break;
...
default:
// 默认代码块
}

catch

  • 用于捕获异常,并进行相应的处理。
1
2
3
4
5
6
7
8
9
try {
// 可能抛出异常的代码
} catch (ExceptionType1 e1) {
// 处理 ExceptionType1 类型的异常
} catch (ExceptionType2 e2) {
// 处理 ExceptionType2 类型的异常
} 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; // ptr1 指向一个常量整数
int* const ptr2 = &y; // ptr2 本身是常量,不能重新指向其他地址
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; // 禁止int类型参数调用

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;

    // 强类型枚举(C++11)
    enum class FileMode { Read, Write, Append };

explicit

  • 禁止构造函数隐式转换
    1
    2
    3
    4
    5
    6
    7
    class MyString {
    public:
    explicit MyString(int size) { /*...*/ }
    };

    // MyString s = 10; // 错误:不能隐式转换
    MyString s(10); // 正确:显式调用

extern

  • 声明外部链接(变量/函数在其他文件定义)
    1
    2
    3
    4
    5
    // header.h
    extern int globalVar; // 声明非定义

    // main.cpp
    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循环
    for(int i=0; i<10; i++) { /*...*/ }

    // 范围for循环(C++11)
    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}; // 可被const函数修改
    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
    int* arr = new int[10]; // 分配数组

    // 智能指针(C++11)
    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

  • 短整型修饰符(通常2字节)
    1
    short daysInWeek = 7;

signed

  • 有符号类型修饰符
    1
    signed char temperature = -5; // 明确有符号

sizeof

  • 获取类型/对象的内存大小
    1
    2
    3
    4
    5
    cout << sizeof(int);    // 输出4(通常)
    cout << sizeof(double); // 输出8(通常)

    int arr[10];
    cout << sizeof(arr); // 输出40(4*10)

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; // 默认public
    };

    // 与class区别:默认访问权限不同

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); // int类型
    cout << max(3.14, 2.99); // double类型

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;

    // C++11更推荐using
    using StringList = vector<string>;

typename

  • 模板中声明类型参数
  • 指示依赖类型名称
    1
    2
    3
    4
    template <typename T>
    class Container {
    typename T::iterator it; // 必须使用typename
    };

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; // 替代NULL
    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; // y的类型为int

    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); // 编译时计算

C++的一些关键字
https://zhxcodes.pages.dev/2025/05/12/C-的一些关键字/
作者
本意
发布于
2025年5月12日
更新于
2025年7月19日
许可协议