语法
基本语法
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <optional>
#include <chrono>
#include <format>
#include <algorithm>
#include <iomanip>
#include <thread>
string name = "张三"; // 常规赋值
auto autoName = "李四"; // 推导为const char*
// 动态数组
vector<int> numbers = {1, 2, 3, 4, 5};
// 传统for循环
for (size_t i = 0; i < numbers.size(); ++i) {
cout << numbers[i] << " ";
}
// if初始化语句(C++17)
if (auto result = numbers.size(); result > 3) {
cout << "数组大小 " << result << " 大于3" << endl;
}
// 结构化绑定(C++17)
pair<string, int> user = {"王五", 28};
auto [userName, userAge] = user; // 类似Python的 name, age = user
cout << "用户: " << userName << ", 年龄: " << userAge << endl;
// 标准输入
string s1, s2;
cin >> s1 >> s2;
// s1 == "Hello"
// s2 == "World"
// 模板函数(类似Java的泛型)可适用任何用'+'的类型
// typename是c++关键字
template<typename T>
T genericSum(T a, T b) {
return a + b;
}
// Lambda表达式(类似Python的lambda)
auto multiply = [](int a, int b) -> int {
return a * b;
};
// 传统枚举(类似Java的enum)
enum class Status {
ACTIVE, // ==0 激活
INACTIVE, // ==1 未激活
PENDING // ==2 待处理
};
// 时间计算
auto start = chrono::high_resolution_clock::now();
// 模拟一些工作
this_thread::sleep_for(chrono::milliseconds(100));
auto end = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>(end - start);
cout << "执行时间: " << duration.count() << " 微秒" << endl;
// C++17 折叠表达式
template<typename... Args>
void call_all(Args&&... args) {
(... , args()); // 调用每个参数的函数
}Lambda
语法:[capture](parameters) -> return_type { body }
// lambda的捕获
void demonstrateLambdaCaptures() {
int x = 10, y = 20, z = 30;
// 1. 不捕获外部变量
auto lambda1 = [](int a, int b) {
return a + b; // 只能使用参数和局部变量
};
// 2. 按值捕获所有变量
auto lambda2 = [=](int a) {
return a + x + y; // x=10, y=20 是拷贝的值
};
// 3. 按引用捕获所有变量
auto lambda3 = [&](int a) {
x = 100; // 修改原变量的值
return a + x;
};
// 4. 混合捕获
auto lambda4 = [x, &y](int a) {
// x按值捕获(只读),y按引用捕获(可修改)
y = a + x;
return y;
};
}异常
try {
int* riskyPtr = new int(200);
throw runtime_error("模拟异常");
} catch (const runtime_error& e) {
cout << "捕获异常: " << e.what() << endl;
}语法关键字
引用 & :给变量起别名 用法:数据类型& 别名 = 原名 引用和指针的区别:https://www.runoob.com/w3cnote/cpp-difference-between-pointers-and-references.html
通常是在函数传值时的差别,直接传参是拷贝变量传递到局部域变量
inline 用于替代C中的宏#define,可以更好地达到#define的效果
友元
friend std::istream &read();在前面声明friend,可以访问到类非公开成员函数
Address::Raw::operator const sockaddr *() const {
return reinterpret_cast<const sockaddr *>(&storage);
}{}前的const是指定return后this指针为指向const的指针
String类
String的几种初始化方式
#include <iostream>
#include <string>
using namespace std;
int main(){
string s1;
string s2 = "c plus plus";
string s3 = s2;
string s4 (5, 's');
return 0;
}智能指针
传统内存管理
// 单一对象
MyClass* obj = new MyClass(arg1, arg2);
delete obj;
obj = nullptr;
// 数组
MyClass* array = new MyClass[10];
delete[] array; // 会调用数组中每个元素的析构
array = nullptr; // 置空释放的指针现代智能指针
{
auto uniqueRes = make_unique<Resource>("unique_resource", 50);
uniqueRes->display(); // 调用对象执行一些方法
cout << "数据大小: " << uniqueRes->getSize() << endl;
cout << "unique_ptr会在作用域结束时自动释放资源" << endl;
}
// uniqueRes在这里被销毁,Resource自动析构智能指针会在作用域结束时自动释放内存,而不需要手动匹配new, free
shared_ptr 和 unique_ptr: shared_ptr可以将指针值赋值给其他指针变量,unique_ptr不能直接复制
auto ptr1 = std::make_shared<MyClass>(42);
// 可以复制给多个 shared_ptr
std::shared_ptr<MyClass> ptr2 = ptr1;
std::shared_ptr<MyClass> ptr3 = ptr2;
// 所有的 shared_ptr 共享同一个对象
ptr1->printValue(); // Value: 42
ptr2->printValue(); // Value: 42
ptr3->printValue(); // Value: 42
std::cout << "ptr1 count: " << ptr1.use_count() << std::endl; // 3
std::cout << "ptr2 count: " << ptr2.use_count() << std::endl; // 3
// 最后一个 shared_ptr 销毁时,对象自动删除如果要复制unique_ptr的值,需要转移所有权
auto ptr1 = std::make_unique<MyClass>();
// 移动所有权
std::unique_ptr<MyClass> ptr2 = std::move(ptr1);
// 现在 ptr1 为 nullptr,ptr2 拥有对象
// 不能再使用 ptr1
if (ptr1 == nullptr) {
std::cout << "ptr1 is empty" << std::endl;
}weak_ptr
弱引用指针用于解决循环引用问题,需要先.lock才可访问且会增加share_ptr的引用计数。
struct Node {
string name;
shared_ptr<Node> next;
weak_ptr<Node> prev; // 使用weak_ptr避免循环引用
Node(const string& n) : name(n) {
cout << "Node " << name << " 构造" << endl;
}
~Node() {
cout << "Node " << name << " 析构" << endl;
}
};
// 创建循环引用(用shared_ptr会有问题,会无法正常释放内存)
cout << "正确的相互引用(使用weak_ptr):" << endl;
{
auto node1 = make_shared<Node>("Node1");
auto node2 = make_shared<Node>("Node2");
node1->next = node2; // shared_ptr引用
node2->prev = node1; // weak_ptr引用
cout << "node1引用计数: " << node1.use_count() << endl;
cout << "node2引用计数: " << node2.use_count() << endl;
// 通过weak_ptr访问前一个节点
if (auto prevNode = node2->prev.lock()) { // lock返回shared_ptr
cout << node2->name << " 的前一个节点是: " << prevNode->name << endl;
}
// lock后shared引用计数增加
}结构体
typedef struct LNode *List;
struct LNode {
ElementType Data[10];
int Last;
};此时List为LNode结构体的指针类型 创建结构体
List MakeEmpty()
{
List node = (List)malloc(sizeof(struct LNode));
node->Last = -1;
return node;
}不可这样创建,这样只是创建了一个局部变量
List MakeEmpty()
{
LNode node;
node.Last = -1;
return &node;
}OOP风格的结构体
struct User {
string name;
int age;
Status status;
double balance;
// 构造
User(const string& n, int a, Status s, double b = 0.0)
: name(n), age(a), status(s), balance(b) {}
// 方法
void printInfo() const {
cout << "用户: " << name
<< ", 年龄: " << age
<< ", 状态: " << static_cast<int>(status)
<< ", 余额: " << balance << endl;
}
// 运算符重载(Go和Python没有的强大特性)
bool operator>(const User& other) const {
return this->balance > other.balance;
}
}
类
使用class和struct仅有默认访问权限的差别,struct默认为public。 继承-多态示例
// 基础抽象类
class Employee {
/*
- private: 仅类内部可访问,类似Java的private
- protected: 类和派生类可访问
- public: 外部可访问
- C++默认class成员为private,struct成员为public
*/
private:
string name;
int id;
double salary;
protected:
// protected成员,派生类可以访问
void setSalary(double newSalary) {
if (newSalary >= 0) {
salary = newSalary;
}
}
public:
// 构造函数
Employee(const string& emp_name, int emp_id, double emp_salary)
: name(emp_name), id(emp_id), salary(emp_salary) {
cout << "创建Employee: " << name << endl;
}
// 基类析构函数必须是virtual
virtual ~Employee() {
cout << "销毁Employee: " << name << endl;
}
// Getter方法
string getName() const { return name; }
int getId() const { return id; }
double getSalary() const { return salary; }
// 普通成员函数
void display() const {
cout << "员工: " << name << ", ID: " << id
<< ", 薪资: " << salary << endl;
}
/*
- virtual: 支持运行时多态
- override: C++11,明确表示重写基类虚函数
- final: C++11,禁止进一步重写
*/
virtual double calculateBonus() const {
return salary * 0.1; // 基础奖金:10%薪资
}
/*
- 纯虚函数 = 0,类变为抽象类
- 类似Java的abstract方法和Python的abstractmethod
- 抽象类不能实例化
*/
virtual void work() = 0;
};
// Manager类继承Employee
class Manager : public Employee {
private:
int teamSize;
double bonusRate;
public:
// 构造函数,调用基类构造函数
Manager(const string& mgr_name, int mgr_id, double mgr_salary,
int mgr_teamSize, double mgr_bonusRate = 0.2)
: Employee(mgr_name, mgr_id, mgr_salary), // 调用基类构造函数
teamSize(mgr_teamSize), bonusRate(mgr_bonusRate) {
cout << "创建Manager: " << mgr_name << endl;
}
// 析构函数
~Manager() override {
cout << "销毁Manager: " << getName() << endl;
}
// 重写虚函数
double calculateBonus() const override {
double baseBonus = getSalary() * 0.15; // 基础奖金15%
double teamBonus = getSalary() * bonusRate * (teamSize / 10.0);
return baseBonus + teamBonus;
}
// 实现纯虚函数
void work() override {
cout << "Manager " << getName() << " 正在管理 "
<< teamSize << " 人的团队" << endl;
}
// 特有的方法
void manageTeam() {
cout << getName() << " 正在召开团队会议" << endl;
}
// 访问基类protected成员
void giveRaise(double amount) {
double newSalary = getSalary() + amount;
setSalary(newSalary); // 调用基类protected方法
cout << getName() << " 获得加薪,新薪资: " << newSalary << endl;
}
}; RAII
Resource Acquisition Is Initialization(RAII) 即在构造时创建资源(如打开文件),析构时释放资源。
class FileHandler {
private:
FILE* file;
string filename;
public:
// RAII:构造函数获取资源
FileHandler(const string& file_name, const string& file_mode = "r")
: filename(file_name) {
file = fopen(file_name.c_str(), file_mode.c_str());
if (!file) {
throw runtime_error("无法打开文件: " + file_name);
}
cout << "打开文件: " << file_name << endl;
}
// RAII:析构函数自动释放资源
~FileHandler() {
if (file) {
fclose(file);
cout << "关闭文件: " << filename << endl;
}
}
}STL
Standard Template Library STL (Standard Template Library) 是C++标准库的核心组成部分,包含:
- 容器 (Containers): 存储数据的对象
- 算法 (Algorithms): 操作容器中数据的函数
- 迭代器 (Iterators): 连接容器和算法的桥梁
- 函数对象 (Function Objects): 可调用的对象
vector: 动态数组
- 连续内存存储,类似Java的ArrayList和Python的list
- 随机访问O(1),插入删除中间O(n)
- 自动扩容,容量通常按2倍增长
- 最常用的容器,性能优异
vector<int> vec = {1, 2, 3, 4, 5};
// 遍历
for (int val : vec) cout << val << " ";
cout << endl;
// 尾部添加元素
vec.push_back(6);
vec.emplace_back(7); // C++11,原地构造
// 弹出尾部并删除元素
vec.pop_back();
map: 有序键值对
- 键值对,按键排序
- 唯一键,类似Java的TreeMap
- O(log n)的查找、插入、删除
map<string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
scores.insert({"Charlie", 92});
cout << "学生成绩:" << endl;
// 使用C++17结构化绑定
for (const auto& [name, score] : scores) {
cout << " " << name << ": " << score << endl;
}
// 查找
if (auto it = scores.find("Alice"); it != scores.end()) {
cout << "Alice的成绩: " << it->second << endl;
}