C++ 极简常用内容

C++ 极简常用内容

1. 类与对象

定义:封装数据(成员变量)和行为(成员函数)的自定义类型。
Demo

class Car {
public:
    string brand;
    void drive() { cout << brand << " is moving." << endl; }
};
int main() {
    Car myCar;
    myCar.brand = "Toyota";
    myCar.drive(); // 输出: Toyota is moving.
}

何时用:表示实体(如用户、订单)或封装逻辑(如文件操作)。


2. 继承

定义:派生类复用基类的属性和方法。
Demo

class Animal {
public:
    void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal {
public:
    void bark() { cout << "Woof!" << endl; }
};
int main() {
    Dog dog;
    dog.eat();  // 继承方法
    dog.bark(); // 自身方法
}

何时用:代码复用(如多种GUI控件共享基类功能)。


3. 多态(虚函数)

定义:通过基类指针/引用调用派生类的重写函数。
Demo

class Shape {
public:
    virtual void draw() { cout << "Drawing shape." << endl; }
};
class Circle : public Shape {
public:
    void draw() override { cout << "Drawing circle." << endl; }
};
int main() {
    Shape* shape = new Circle();
    shape->draw(); // 输出: Drawing circle.
    delete shape;
}

何时用:统一接口不同实现(如游戏角色行为差异)。


4. 模板(泛型编程)

定义:编写与类型无关的代码。
Demo

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

int main() {
    cout << max(3, 5) << endl;     // 输出: 5
    cout << max(3.14, 2.71) << endl; // 输出: 3.14
}

何时用:通用容器(如vector<T>)或算法(如排序)。


5. 智能指针

定义:自动管理动态内存,避免泄漏。
Demo

#include <memory>
class Resource {};
int main() {
    std::unique_ptr<Resource> res = std::make_unique<Resource>();
    // 离开作用域自动释放内存
}

何时用

  • unique_ptr:独占资源(如文件句柄)。
  • shared_ptr:共享资源(如缓存数据)。

6. STL 容器

核心容器

  • vector:动态数组(快速随机访问)。
  • map:有序键值对(基于红黑树)。
  • unordered_map:哈希表实现的键值对(更快查找)。

Demo

#include <vector>
#include <unordered_map>
int main() {
    vector<int> nums = {1, 2, 3};
    unordered_map<string, int> ages = {{"Alice", 25}, {"Bob", 30}};
}

何时用

  • vector:需动态扩容的数组。
  • unordered_map:快速键值查找(如缓存)。

7. RAII(资源管理)

定义:通过对象生命周期管理资源(如内存、文件)。
Demo

class FileHandler {
    FILE* file;
public:
    FileHandler(const char* path) { file = fopen(path, "r"); }
    ~FileHandler() { fclose(file); }
};
int main() {
    FileHandler fh("data.txt"); // 文件自动关闭
}

何时用:资源需自动释放(如数据库连接、锁)。


速查表

概念常用内容典型场景
类与对象封装数据和行为实体建模(如用户类)
继承class B : public A代码复用(如GUI控件继承)
多态virtual + override统一接口不同实现(如游戏角色)
模板template <typename T>泛型容器/算法(如vector<T>
智能指针unique_ptr, shared_ptr自动内存管理
STL容器vector, map, unordered_map数据存储与快速查找
RAII构造函数分配,析构函数释放文件、网络连接管理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值