跳到主要内容

C++ 知识速查表

本页面汇总了 C++ 编程中最常用的语法和知识点,方便快速查阅。

基本语法

Hello World

#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}

命名空间

// 完整写法
std::cout << "hello" << std::endl;

// using 声明
using std::cout;
using std::endl;
cout << "hello" << endl;

// using 命名空间(慎用)
using namespace std;

数据类型

基本类型

类型大小说明
char1字节字符
short2字节短整数
int4字节整数
long4/8字节长整数
long long8字节64位整数
float4字节单精度浮点
double8字节双精度浮点
bool1字节布尔值

常用类型定义

#include <cstdint>

int8_t // 8位有符号整数
int16_t // 16位有符号整数
int32_t // 32位有符号整数
int64_t // 64位有符号整数
uint8_t // 8位无符号整数
size_t // 无符号整数(用于大小)

// auto 类型推导
auto a = 10; // int
auto b = 3.14; // double

类型转换

// 隐式转换
int a = 10;
double b = a; // int → double

// 显式转换(强制类型转换)
double c = 3.14;
int d = (int)c; // 3
int e = static_cast<int>(c); // 推荐

// 其他转换方式
const_cast<T> // 去除 const
reinterpret_cast<T> // 重新解释内存
dynamic_cast<T> // 运行时检查

数组和指针

数组

// 静态数组
int arr[5] = {1, 2, 3, 4, 5};
int arr2[] = {1, 2, 3};

// 动态数组(C++11)
std::vector<int> vec = {1, 2, 3, 4, 5};

// 多维数组
int matrix[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};

指针

int value = 10;
int* ptr = &value; // 取地址
int val = *ptr; // 解引用

// 指针运算
ptr++; // 移动到下一个元素
ptr--; // 移动到上一个元素

// 空指针
int* p = nullptr;

引用

int value = 10;
int& ref = value; // 引用
ref = 20; // 修改原值

// 函数参数传递
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}

控制流

条件语句

// if-else
if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}

// switch
switch (value) {
case 1:
// code
break;
case 2:
// code
break;
default:
// code
}

// 三目运算符
int max = (a > b) ? a : b;

循环

// for 循环
for (int i = 0; i < 10; i++) {
// code
}

// 范围 for(C++11)
for (int x : arr) {
// code
}

// while
while (condition) {
// code
}

// do-while(至少执行一次)
do {
// code
} while (condition);

函数

函数定义

// 普通函数
int add(int a, int b) {
return a + b;
}

// 默认参数
void print(int n, int base = 10) {
// code
}

// 函数重载
int add(int a, int b);
double add(double a, double b);

// 模板函数
template<typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}

// Lambda
auto lambda = [](int x) { return x * 2; };

参数传递

// 值传递
void func1(int value);

// 指针传递
void func2(int* ptr);

// 引用传递
void func3(int& ref);

// const 引用
void func4(const std::string& str);

类与对象

类定义

class Rectangle {
private:
double width;
double height;

public:
// 构造函数
Rectangle() : width(0), height(0) {}
Rectangle(double w, double h) : width(w), height(h) {}

// 成员函数
double area() const { return width * height; }
void setSize(double w, double h) {
width = w;
height = h;
}

// 析构函数
~Rectangle() {}
};

访问控制

class MyClass {
public: // 公有成员:任意访问
int publicMember;

private: // 私有成员:仅本类访问
int privateMember;

protected: // 保护成员:本类和派生类访问
int protectedMember;
};

特殊成员函数

class MyClass {
public:
// 构造函数
MyClass();
MyClass(int v);

// 拷贝构造函数
MyClass(const MyClass& other);

// 移动构造函数(C++11)
MyClass(MyClass&& other) noexcept;

// 拷贝赋值
MyClass& operator=(const MyClass& other);

// 移动赋值(C++11)
MyClass& operator=(MyClass&& other) noexcept;

// 析构函数
~MyClass();
};

运算符重载

class Complex {
private:
double real, imag;

public:
// 加法
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}

// 输出流
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
};

继承与多态

继承

class Base {
public:
virtual void func() {}
};

class Derived : public Base {
public:
void func() override {} // 重写
};

// 使用多态
Base* ptr = new Derived();
ptr->func(); // 调用 Derived 的版本

虚函数

class Base {
public:
virtual void func() { // 虚函数
std::cout << "Base" << std::endl;
}

virtual ~Base() {} // 虚析构函数
};

class Derived : public Base {
public:
void func() override {
std::cout << "Derived" << std::endl;
}
};

纯虚函数与抽象类

class Shape {
public:
virtual double area() const = 0; // 纯虚函数
virtual ~Shape() = default;
};

// 抽象类不能实例化
// Shape s; // 错误!

class Circle : public Shape {
public:
double area() const override { return r * r * 3.14; }
};

STL 容器

顺序容器

std::vector<int> v;     // 动态数组
std::deque<int> d; // 双端队列
std::list<int> l; // 双向链表
std::array<int, 5> a; // 固定数组

关联容器

std::set<int> s;                // 集合
std::multiset<int> ms; // 多重集合
std::map<string, int> m; // 映射
std::multimap<string, int> mm; // 多重映射

// 无序容器(C++11)
std::unordered_set<int> us;
std::unordered_map<string, int> um;

容器操作

// 添加
v.push_back(1);
v.insert(v.begin(), 0);

// 删除
v.pop_back();
v.erase(v.begin());

// 访问
v[0];
v.at(0);
v.front();
v.back();

// 大小
v.size();
v.empty();

算法

常用算法

#include <algorithm>

// 排序
std::sort(v.begin(), v.end()); // 升序
std::sort(v.begin(), v.end(), std::greater<int>()); // 降序

// 查找
auto it = std::find(v.begin(), v.end(), 5);
auto it = std::binary_search(v.begin(), v.end(), 5); // 需要已排序

// 变换
std::transform(v.begin(), v.end(), v.begin(),
[](int x) { return x * 2; });

// 删除
v.erase(std::remove_if(v.begin(), v.end(),
[](int x) { return x % 2 == 0; }),
v.end());

智能指针

#include <memory>

// unique_ptr(独占所有权)
auto p1 = std::make_unique<int>(10);
std::unique_ptr<int> p2(new int(20));

// shared_ptr(共享所有权)
auto sp1 = std::make_shared<int>(30);
std::shared_ptr<int> sp2(sp1);

// weak_ptr(观察者)
std::weak_ptr<int> wp = sp1;
auto sp = wp.lock(); // 转为 shared_ptr

模板

函数模板

template<typename T>
T max(T a, T b) {
return a > b ? a : b;
}

// 调用
max(1, 2); // T = int
max(1.0, 2.0); // T = double

类模板

template<typename T>
class Stack {
private:
std::vector<T> data;

public:
void push(const T& item) { data.push_back(item); }
T pop() {
T item = data.back();
data.pop_back();
return item;
}
};

// 使用
Stack<int> s;
Stack<std::string> ss;

可变参数模板(C++11)

template<typename... Args>
void print(Args... args) {
((std::cout << args << " "), ...);
std::cout << std::endl;
}

Modern C++ 特性

auto 和 decltype

auto a = 10;      // 自动推导类型
auto b = 3.14;
auto c = "hello";

decltype(a) d = 20; // 获取表达式类型

范围 for

for (int x : v) {
std::cout << x << " ";
}

// 使用引用修改
for (auto& x : v) {
x *= 2;
}

结构化绑定(C++17)

std::map<string, int> m;
for (const auto& [key, value] : m) {
std::cout << key << ": " << value << std::endl;
}

if constexpr(C++17)

template<typename T>
void print(const T& val) {
if constexpr (std::is_integral_v<T>) {
std::cout << "Integer: " << val << std::endl;
} else {
std::cout << "Other: " << val << std::endl;
}
}

concepts(C++20)

#include <concepts>

template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

Numeric auto add(Numeric auto a, Numeric auto b) {
return a + b;
}

多线程

#include <thread>
#include <mutex>
#include <atomic>

// 创建线程
std::thread t([](){ /* code */ });
t.join(); // 等待结束

// 互斥锁
std::mutex mtx;
std::lock_guard<std::mutex> lock(mtx);

// 原子操作
std::atomic<int> counter(0);
counter.fetch_add(1);

常见错误

内存泄漏

// 错误
int* p = new int(10);
// 忘记 delete

// 正确:使用智能指针
auto p = std::make_unique<int>(10);

悬空指针

// 错误
int* p = new int(10);
delete p;
*p = 20; // 访问已释放的内存

// 正确:delete 后置空
int* p = new int(10);
delete p;
p = nullptr;

循环引用

// 使用 weak_ptr 打破循环引用
class Node {
public:
std::weak_ptr<Node> next;
std::weak_ptr<Node> prev;
};

常用头文件

#include <iostream>     // 输入输出
#include <vector> // 动态数组
#include <string> // 字符串
#include <algorithm> // 算法
#include <memory> // 智能指针
#include <thread> // 线程
#include <mutex> // 互斥锁
#include <map> // 映射
#include <set> // 集合
#include <functional> // 函数对象
#include <cmath> // 数学函数