1.
auto
关键字:用于自动推断变量类型。
auto x = 10; // 自动推断变量类型为 int
auto y = 3.14; // 自动推断变量类型为 double
2.
const
关键字:用于声明为可读常量。
const int x = 10; // x 为常量,不能被修改
3.
constexpr
关键字:用于声明编译时常量。
constexpr int x = 10; // x 为编译时常量,可以在编译时进行计算
4.
static
关键字:用于声明静态成员变量。
class MyClass {
public:
static int x; // 声明静态成员变量 x
};
int MyClass::x = 10; // 初始化静态成员变量 x
5.
inline
关键字:用于声明内联函数 。
inline int add(int a, int b) { // 声明内联函数 add
return a + b;
}
6.
const
和volatile
关键字:用于声明非常量变量和声明对变量的可见性进行限制。
const volatile int x = 10; // x 为非常量变量,但对其可见性进行限制
7.
enum
关键字:用于声明枚举类型。
enum Color { RED, GREEN, BLUE }; // 声明枚举类型 Color
8.
struct
和class
关键字:用于声明结构体和类。
struct Point {
int x;
int y;
}; // 声明结构体 Point
class Rectangle {
public:
int width;
int height;
}; // 声明类 Rectangle
9.typedef
关键字:用于声明类型别名。
typedef unsigned int uint; // 声明类型别名 uint
10.
sizeof
关键字:用于获取变量或类型的大小
size_t size = sizeof(int); // 获取 int 类型的大小
11.
typeid
关键字:用于获取对象的类型。
typeid_t typeid = typeid(x); // 获取对象 x 的类型
12.
new
和delete
关键字:用于分配和释放动态内存。
int *x = new int(10); // 分配动态内存 x
delete x; // 释放动态内存 x
13.
static_assert
关键字:用于进行编译时断言。
static_assert(sizeof(int) == sizeof(float), "Size of int and float must be the same"); // 进行编译时断言
14.
noexcept
关键字:用于声明异常处理规则。
void foo() noexcept { // 声明异常处理规则
// ...
}
15.
try
、catch
和throw
关键字:用于异常处理。
try {
// ...
} catch (Exception &e) {
// ...
} throw Exception("An error occurred"); // 抛出异常