入门
Hello World
每个 C++ 程序都从 main() 开始。<iostream> 提供了 std::cout(标准输出)和 std::cin(标准输入)。std:: 前缀指向标准命名空间;使用 using namespace std; 可以省略它,但不建议在头文件中使用,因为这会污染全局命名空间。
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}变量与 auto
auto 会根据初始化器推导类型(C++11)。当类型显而易见或过于冗长时(如迭代器)使用 auto。const 使值不可变;constexpr 在编译时求值,用于嵌入二进制文件中的真正常量。
int age = 30;
double pi = 3.14159;
char grade = 'A';
bool is_dev = true;
std::string name = "Alice";
auto x = 42; // int
auto y = 3.14; // double
const double TAX = 0.08;输入与输出
std::getline 读取整行(包括空格),而 std::cin >> 在空白字符处停止。混合使用两者会在缓冲区中留下换 行符;在 getline 和 >> 之间调用 std::cin.ignore() 可丢弃它。
#include <iostream>
#include <string>
int main() {
std::string name;
int age;
std::cout << "Name: ";
std::getline(std::cin, name);
std::cout << "Age: ";
std::cin >> age;
std::cout << "Hi " << name << ", " << age << "\n";
}引用
引用是必须初始化且不能重新绑定到其他对象的别名。按引用传递可避免拷贝并允许修改调用者的变量。对于只读参数使用 const T& 以避免昂贵的拷贝。
int x = 10;
int &ref = x; // alias for x
ref = 20;
std::cout << x; // 20
void increment(int &n) { n++; }
int a = 5;
increment(a); // a is now 6类型转换
优先使用 static_cast 而非 C 风格转换,因为它是显式的并在编译时检查,使意图清晰。std::stoi、std::stod 将字符串转换为数字;std::to_string 执行反向操作。注意错误输入时的 std::out_of_range 异常。
double d = 3.99;
int i = (int)d; // C-style: 3
int j = static_cast<int>(d); // C++: 3
int n = 65;
char c = static_cast<char>(n); // 'A'
// string <-> number
int num = std::stoi("42");
std::string s = std::to_string(3.14);字符串
std::string 基础
std::string 自行管理内存并按需增长。与 C 字符数组不同,你无需手动管理长度。当未找到子字符串时,.find() 返回 std::string::npos(一个巨大的值),因此始终与 npos 比较。
#include <string>
std::string s = "Hello";
std::cout << s.length(); // 5
std::cout << s[0]; // H
s += ", World!";
std::cout << s; // Hello, World!
std::cout << s.substr(0, 3); // Hel
std::cout << s.find("World"); // 7比较与查找
比较是按字典序进行的。.find() 向前搜索,.rfind() 向后搜索。两者在未找到时都返回 std::string::npos,因此始终与 npos 比较,而不是将结果作为布尔值处理。
std::string a = "apple", b = "banana";
if (a == b) { /* equal */ }
if (a < b) { /* apple comes before banana */ }
if (a.find("pp") != std::string::npos) {
std::cout << "found\n";
}
size_t pos = a.rfind("p"); // last occurrenceStringstream
stringstream 在字符串和类型化值之间架起桥梁,适用于构建格式化字符串(类似缓冲区)或解析以空白分隔的标记。它比直接操作慢,但在序列化和反序列化方面非常灵活。
#include <sstream>
// Build a string
std::ostringstream oss;
oss << "Name=" << "Alice" << "&Age=" << 30;
std::string result = oss.str();
// Parse tokens
std::istringstream iss("10 20 30");
int a, b, c;
iss >> a >> b >> c; // a=10, b=20, c=30原始字符串与多行字符串
原始字符串字面量 R"(...)" 将反 斜杠和引号按字面值处理,非常适合正则表达式模式、Windows 文件路径和 JSON/XML 模板。括号内的分隔符是任意的,例如 R"x(...)x" 以允许内部包含 )。
std::string raw = R"(C:\Users\name\file.txt)";
// No need to escape backslashes
std::string json = R"({
"name": "Alice",
"age": 30
})";char 数组与 std::string
C 风格 char 数组需要手动管理大小且容易出错(缓冲区溢出)。优先使用 std::string;在与期望 const char* 的 C API 交互时使用 .c_str()。注意 c_str() 仅在字符串存活且未被修改时有效。
char cstr[] = "Hello"; // null-terminated, size 6
std::string cppstr = "Hello";
#include <cstring>
std::cout << strlen(cstr); // 5
std::cout << cppstr.length(); // 5
std::string from_c = cstr; // C -> C++
const char* to_c = cppstr.c_str(); // C++ -> C数字与数学
整数与浮点类型
当跨平台需要精确大小时,使用 <cstdint> 固定宽度类型(int32_t、int64_t)。' 数字分隔符(C++14)可提高大数字的可读性。double 是默认浮点类型,在精度方面优于 float。
#include <cstdint>
int32_t a = 100;
int64_t big = 9'000'000'000LL;
uint8_t byte = 255;
size_t sz = sizeof(a); // 4
float f = 1.5f; // 4 bytes
double d = 3.14159265; // 8 bytes (preferred)数值限制
<limits> 提供数值属性的类型特征。使用这些而不是硬编码的 INT_MAX 宏。epsilon() 给出浮点可区分的最小差值,适用于带容差比较 double。
#include <limits>
std::cout << std::numeric_limits<int>::max(); // 2147483647
std::cout << std::numeric_limits<int>::min(); // -2147483648
std::cout << std::numeric_limits<double>::infinity();
std::cout << std::numeric_limits<double>::epsilon();数学函数
<cmath> 提供标准数学函数。C++ 中整数溢出是未定义行为;使用 int64_t 或检查边界。对于金融代码,请记住浮点数不精确——考虑使用整数分或十进制库。
#include <cmath>
double x = 2.5;
std::pow(x, 3); // 15.625
std::sqrt(x); // 1.581
std::abs(-5); // 5
std::floor(3.7); // 3.0
std::ceil(3.2); // 4.0
std::round(3.5); // 4.0
std::fmod(10.5, 3); // 1.5随机数
现代 C++ 使用 <random> 库代替 rand()。mt19937 是高质量的伪随机数生成器。分布(uniform_int、uniform_real、normal)将原始位映射到所需范围,避免了 rand() % N 的取模偏差问题。
#include <random>
std::random_device rd;
std::mt19937 gen(rd()); // Mersenne Twister engine
std::uniform_int_distribution<int> dist(1, 100);
for (int i = 0; i < 5; i++) {
std::cout << dist(gen) << " ";
}整数溢出与转换
有符号整数溢出在 C++ 中是未定义行为(编译器可能假设它从不发生而进行优化)。在乘法前始终转换为更宽的类型,或检查边界 。无符号溢出按 2^n 取模回绕,是明确定义的。
int a = 100'000;
int b = a * a; // overflow! undefined behavior
long long safe = (long long)a * a; // OK
// Check before multiplying
if (a > 0 && b > INT_MAX / a) {
// would overflow, handle it
}控制流
If / Else
C++17 引入带初始化器的 if:if (auto it = m.find(k); it != m.end()) { ... }。这会将变量作用域限制在 if/else 块内,保持周围作用域清洁并避免意外重用。
int score = 85;
if (score >= 90) {
std::cout << "A\n";
} else if (score >= 80) {
std::cout << "B\n";
} else {
std::cout << "C\n";
}Switch
始终包含 break 以防止意外的 fall-through。C++17 [[fallthrough]] 属性用于记录有意的 fall-through 以消除警告。switch 适用于整型和枚举类型,不适用于字符串或浮点数。
int day = 3;
switch (day) {
case 1: std::cout << "Mon"; break;
case 2: std::cout << "Tue"; break;
case 3: std::cout << "Wed"; break;
default: std::cout << "Other";
}For 循环
范围 for 循环可干净地迭代容器。使用 const auto& 避免拷贝元素(对字符串和大对象很重要)。要就地修改元素,使用 auto&(非 const 引用)。
// Classic for
for (int i = 0; i < 5; i++) {
std::cout << i << " ";
}
// Range-based for (C++11)
std::vector<int> v = {1, 2, 3};
for (int n : v) std::cout << n;
for (const auto &n : v) std::cout << n; // no copyWhile 与 Do-While
while 在执行前检查条件;do-while 在检查前至少执行一次循环体。do-while 适用于输入验证和菜单循环,这些场景中循环体必须在条件可求值前运行。
int n = 5;
while (n > 0) {
std::cout << n-- << " ";
}
int x;
do {
std::cin >> x;
} while (x < 0); // runs at least onceBreak、Continue 与嵌套循环
break 退出最近的封闭循环;continue 跳到下一次迭代。C++ 没有像 Java 那样的带标签 break;使用标志变量,或将循环提取为函数并使用 return 跳出嵌套循环。
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // skip 3
if (i == 7) break; // stop at 7
std::cout << i << " "; // 0 1 2 4 5 6
}
// C++ has no labeled break; use a flag
bool found = false;
for (int i = 0; i < n && !found; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == target) { found = true; break; }
}
}函数与 Lambda
定义与多返回值
C++17 结构化绑定(auto [a, b] = ...)可干净地解包元组、pair 和结构体。在 C++17 之前,使用 std::tie 或输出参数。由于 移动语义(RVO)会省略拷贝,按值返回开销很小。
#include <tuple>
std::tuple<int, int> divide(int a, int b) {
return {a / b, a % b};
}
auto [q, r] = divide(17, 5); // q=3, r=2 (C++17)默认参数与 inline
默认参数允许调用者省略尾部参数。inline 是给编译器的提示,要求内联展开函数;现代编译器根据优化标志自行决定内联,因此 inline 主要与 ODR(单一定义规则)有关。
inline int power(int base, int exp = 2) {
int r = 1;
for (int i = 0; i < exp; i++) r *= base;
return r;
}
// power(3) == 9, power(2, 5) == 32函数重载
重载允许函数共享名称但参数类型不同。编译器通过重载解析选择最佳匹配。歧义重载会导致编译错误;当函数体在不同类型间相同时,优先使用模板。
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
std::string add(std::string a, std::string b) { return a + b; }
add(1, 2); // int version
add(1.5, 2.5); // double version
add("a", "b"); // string versionLambda 表达式
Lambda 内联创建匿名函数对象。[] 捕获变量:[=] 按值捕获,[&] 按引用捕获,[x] 按值捕获特定变量,[&x] 按引用捕获特定变量。它们对 STL 算法和回调至关重要。按引用捕获时注意悬空引用。
auto square = [](int x) { return x * x; };
std::cout << square(5); // 25
int factor = 3;
auto multiply = [factor](int x) { return x * factor; };
std::vector<int> v = {1, 2, 3};
std::for_each(v.begin(), v.end(), [](int n) {
std::cout << n << " ";
});函数指针与 std::function
std::function(来自 <functional>)可持有任何可调用对象:函数、lambda、仿函数。它比原始函数指针更灵活,但由于类型擦除有少量运行时开销。用于回调和在容器中存储可调用对象。
#include <functional>
int add(int a, int b) { return a + b; }
int (*fp)(int, int) = add; // raw function pointer
std::function<int(int, int)> f = add; // flexible wrapper
f = [](int a, int b) { return a * b; };
std::cout << f(3, 4); // 12STL 容器
vector
vector 是动态数组,是默认的容器选择。push_back 是摊销 O(1)。.at() 进行边界检查(抛出 std::out_of_range),operator[] 不检查。如果知道大小,预先调用 reserve() 可避免重新分配。
#include <vector>
std::vector<int> v = {1, 2, 3};
v.push_back(4);
v.pop_back();
v.size(); // 3
v[0] = 0;
v.at(5); // throws std::out_of_range
for (int n : v) std::cout << n;map 与 unordered_map
map 保持键有序(O(log n) 操作);unordered_map 使用哈希(平均 O(1))。需要有序迭代或范围查询时使用 map;纯查找速度时使用 unordered_map。迭代 unordered_map 是无序的。
#include <map>
#include <unordered_map>
std::map<std::string, int> ordered; // sorted by key (red-black tree)
ordered["Alice"] = 30;
std::unordered_map<std::string, int> hashed; // hash table
hashed["Bob"] = 25;
for (auto &[k, v] : ordered) { // C++17 structured binding
std::cout << k << ":" << v;
}set 与 unordered_set
set 存储唯一的有序元素(O(log n))。unordered_set 是基于哈希的版本(平均 O(1))。用于去重和成员测试。lower_bound/upper_bound 可在有序集合上执行范围查询。
#include <set>
std::set<int> s = {3, 1, 4, 1, 5};
// s contains: 1, 3, 4, 5 (sorted, unique)
s.insert(2);
s.erase(1);
if (s.count(4)) std::cout << "found";
auto it = s.lower_bound(3); // first >= 3array 与 deque
array 是固定大小的栈分配数组,具有 STL 接口(比 C 数组更安全,不会退化为指针)。deque(双端队列)支持两端 O(1) 的 push/pop,而 vector 在前端是 O(n)。
#include <array>
#include <deque>
std::array<int, 3> arr = {1, 2, 3}; // fixed size, stack-allocated
arr.size(); // 3
std::deque<int> dq = {1, 2, 3};
dq.push_front(0);
dq.push_back(4);
// dq: 0, 1, 2, 3, 4tuple 与 pair
tuple 持有任意类型的异构值。pair 是二元 tuple。结构化绑定(C++17)将它们分解为命名变量。在迭代元素为 (key, value) pair 的 map 时很常见。
#include <tuple>
std::tuple<int, std::string, double> t = {1, "Alice", 3.14};
auto [id, name, val] = t; // C++17 structured binding
std::pair<int, int> p = {1, 2};
std::cout << p.first << p.second;
auto [a, b] = std::make_pair(10, 20);指针与内存
原始指针
指针存储内存地址。& 获取地址,* 解引用。指针算术适用于数组。原始指针不跟踪所有权,会导致泄漏和悬空指针——对于拥有的资源优先使用智能指针。
int x = 10;
int *ptr = &x; // address of x
std::cout << *ptr; // 10 (dereference)
*ptr = 20;
std::cout << x; // 20
int arr[] = {1, 2, 3};
int *p = arr;
std::cout << *(p + 1); // 2引用与指针
引用更安全(永不为 null,始终有效)且语法更清晰。函数参数和返回值使用引用。当 null 是有意义的状态或需要重新指向时使用指针。
int x = 10;
int &ref = x; // must init, cannot reseat
int *ptr = &x; // can be null, can reassign
ref = 20; // x = 20
*ptr = 30; // x = 30
// References cannot be null, safer for parameters
void foo(const std::string &s); // preferred
void bar(std::string *s); // s might be nullunique_ptr
unique_ptr 独占堆对象的所有权。它不能被拷贝,只能移动。超出作用域时自动删除(RAII)。这是大多数用例的默认智能指针——相比原始指针零开销。
#include <memory>
auto p = std::make_unique<int>(42);
std::cout << *p; // 42
// auto p2 = p; // ERROR: cannot copy
auto p2 = std::move(p); // transfer ownership
// p is now nullptrshared_ptr 与 weak_ptr
shared_ptr 使用引用计数;当最后一个 shared_ptr 被销毁时对象被释放。weak_ptr 在不影响计数的情况下观察,打破引用循环。避免 shared_ptr 的循环引用(它们会泄漏,因为计数永远不为零)。
#include <memory>
auto a = std::make_shared<int>(42);
auto b = a; // both point to same object
std::cout << a.use_count(); // 2
std::weak_ptr<int> w = a; // observer, no ownership
if (auto locked = w.lock()) {
std::cout << *locked; // 42
}RAII 与 new/delete
RAII 将资源生命周期与对象作用域绑定:构造函数获取,析构函数释放。这保证了即使异常传播时也能清理。优先使用 vector 和智能指针而非手动 new/delete——它们为你实现了 RAII。
// Manual new/delete (avoid in modern C++)
int *p = new int(42);
delete p;
// RAII: resource acquisition is initialization
class Buffer {
int *data;
public:
Buffer(size_t n) : data(new int[n]) {}
~Buffer() { delete[] data; } // auto cleanup
};
// Modern: use containers/smart pointers instead
std::vector<int> buf(100); // no manual delete needed类与面向对象
类与构造函数
成员初始化列表(: name(...), age(...))在函数体运行前初始化成员,比在函数体中赋值更高效。将 getter 标记为 const 以允许在 const 对象上调用。std::move 避免拷贝字符串参数。
class Person {
std::string name;
int age;
public:
Person(std::string n, int a) : name(std::move(n)), age(a) {}
std::string getName() const { return name; }
int getAge() const { return age; }
};
Person p("Alice", 30);
std::cout << p.getName();访问修饰符与封装
private 成员只能在类内访问;protected 允许子类访问;public 对所有开放。封装隐藏实现细节,暴露稳定接口。默认使用 private,仅暴露必要的部分。
class Account {
private:
double balance;
protected:
std::string owner;
public:
Account(double b) : balance(b) {}
double getBalance() const { return balance; }
void deposit(double amt) { if (amt > 0) balance += amt; }
};继承与 virtual
virtual 启用运行时多态——通过 Animal* 调用 speak() 会分派到 Dog 的版本。始终在基类中声明 virtual 析构函数,以便通过基类指针删除时调用派生类析构函数。override 可捕获拼写错误。
class Animal {
public:
virtual void speak() { std::cout << "..."; }
virtual ~Animal() = default; // virtual destructor!
};
class Dog : public Animal {
public:
void speak() override { std::cout << "Woof"; }
};
Animal *a = new Dog();
a->speak(); // Woof (polymorphism)
delete a;抽象类与接口
纯虚函数(= 0)使类成为抽象的——你不能实例化它。只有纯虚函数的类就像 Java 接口。具体子类必须实现所有纯虚函数,否则它们仍然是抽象的。
class Shape {
public:
virtual double area() const = 0; // pure virtual
virtual ~Shape() = default;
};
class Circle : public Shape {
double r;
public:
Circle(double r) : r(r) {}
double area() const override {
return 3.14159 * r * r;
}
};运算符重载
运算符重载允许用户类型与 +、<<、== 等一起工作。仅当含义直观时(数学类型、迭代器)才重载。<< 运算符通常 通过 friend 为流输出重载,使 cout << myObject 成为可能。
class Vec2 {
double x, y;
public:
Vec2(double x, double y) : x(x), y(y) {}
Vec2 operator+(const Vec2 &o) const {
return {x + o.x, y + o.y};
}
friend std::ostream &operator<<(std::ostream &os, const Vec2 &v) {
return os << "(" << v.x << "," << v.y << ")";
}
};
Vec2 a(1, 2), b(3, 4);
std::cout << a + b; // (4,6)模板与泛型
函数模板
函数模板在编译时生成类型特定的版本。编译器从参数推导 T;你也可以显式指定。模板是零成本抽象——没有运行时开销,但会增加编译时间和二进制大小。
template <typename T>
T max_val(T a, T b) {
return (a > b) ? a : b;
}
std::cout << max_val(3, 7); // int: 7
std::cout << max_val(3.14, 2.71); // double: 3.14
std::cout << max_val<std::string>("a", "b"); // explicit类模板
类模板将整个类按类型参数化。标准容器(vector、map)都是模板。模板代码必须在头文件中(或使用显式实例化),因为编译器需要完整定义来生成代码。