考场防编译错误专用。按"你想写什么"查找,每条都给出完整正确语法和常见错误写法对比。
配合 模板速查手册.md(高层套路)使用,本卡专注语法细节。


目录


1. 头文件:该 include 什么

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>    // cin, cout, endl, cerr
#include <string> // string 类
#include <vector> // vector
#include <algorithm> // sort, find, count, count_if, max_element, min_element, reverse, swap
#include <queue> // queue, priority_queue, deque
#include <stack> // stack
#include <map> // map, multimap
#include <set> // set, multiset
#include <cmath> // sqrt, pow, abs(float), ceil, floor, round
#include <cstdlib> // abs(int), rand, srand, atoi, exit
#include <cctype> // isalpha, isdigit, isalnum, isspace, toupper, tolower
#include <cstring> // strlen, strcpy, strcmp, strcat, memset, memcpy (C 风格字符串)
#include <numeric> // accumulate, partial_sum (容易忘!)
#include <iomanip> // setw, setprecision, fixed, setfill, left, right, showpoint
#include <climits> // INT_MAX, INT_MIN
#include <functional> // greater<int>, less<int> (priority_queue 小顶堆用)

容易忘的头文件对照:

你要用什么 必须 include 忘了会怎样
accumulate <numeric> 'accumulate' was not declared
sqrt, pow <cmath> 'sqrt' was not declared
isalpha, isdigit, toupper <cctype> 'isalpha' was not declared
abs(整数) <cstdlib> 或 <cmath> 'abs' was not declared
setw, setprecision <iomanip> 'setw' was not declared
INT_MAX <climits> 'INT_MAX' was not declared
greater<int> <functional> 'greater' was not declared
stoi, to_string <string> (已含) 一般不会忘
strlen 等C函数 <cstring> 'strlen' was not declared

建议:考试时一股脑全 include,不省那几行。宁可多 include 也不报错。


2. 头文件保护写法

1
2
3
4
5
6
7
8
9
10
11
12
// 方法1:#ifndef(最保险,所有编译器都支持)
#ifndef MYCLASS_H
#define MYCLASS_H

// ... 类声明 ...

#endif

// 方法2:#pragma once(简洁,主流编译器都支持)
#pragma once

// ... 类声明 ...

错误写法 vs 正确写法:

1
2
3
4
5
6
7
8
9
// ❌ 忘了保护 → 重复 include 时重定义报错
// MyClass.h
class MyClass { ... };

// ✅ 正确
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass { ... };
#endif

前向声明(解决两个类互相引用):

1
2
3
4
5
6
// A.h 里需要用到 B 但不能 include B.h(会循环)
class B; // 前向声明,只说"有这个类"
class A {
B* b; // 只能用指针/引用,不能直接 B b;
};
// A.cpp 里再 #include "B.h" 使用 B 的具体成员

3. 变量与类型声明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 基本类型
int a = 10;
double b = 3.14;
char c = 'A';
bool flag = true;
string s = "hello";

// 数组
int arr[100]; // 固定数组
int arr[] = {1, 2, 3}; // 初始化列表
int arr[5] = {0}; // 全部初始化为 0
char str[] = "hello"; // C 字符串,自动加 '\0',长度 6

// 二维数组
int matrix[10][20];
int m[][3] = {{1,2,3}, {4,5,6}}; // 第二维必须写

// 指针
int* p; // 指针
int* arr = new int[100]; // 动态数组
int** mat = new int*[n]; // 动态二维数组第一层

// 引用(必须初始化)
int x = 10;
int& ref = x; // ref 是 x 的别名

易错对比:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ❌ 引用不初始化
int& ref; // 错!引用必须初始化

// ❌ const 常量不初始化
const int SIZE; // 错!const 必须初始化

// ❌ 数组大小用变量(非 constexpr)
int n; cin >> n;
int arr[n]; // 可能编译过但非标准!用 vector 代替

// ✅ 正确
int n; cin >> n;
vector<int> v(n); // 用 vector

// ✅ constexpr 常量可以当数组大小
constexpr int SIZE = 100;
int arr[SIZE]; // 正确

4. 函数:声明/定义/默认参数/重载

4.1 函数声明与定义分离

1
2
3
4
5
6
7
8
9
10
11
// 声明(放 .h)
int add(int a, int b);
void print(int x);

// 定义(放 .cpp)
int add(int a, int b) {
return a + b;
}
void print(int x) {
cout << x << endl;
}

4.2 默认参数(只在声明写一次!)

1
2
3
4
5
6
7
// .h 声明
void func(int a, int b = 10, const string& s = "default");

// .cpp 定义(不能再写默认值!)
void func(int a, int b, const string& s) { // ❌ 不能写 = 10, = "default"
cout << a << " " << b << " " << s << endl;
}

错误:

1
2
3
4
5
6
7
8
9
// ❌ 声明和定义都写了默认值
// .h: void func(int a, int b = 10);
// .cpp: void func(int a, int b = 10) {} ← 重定义默认值,报错!

// ❌ 默认参数从右往左连续
void func(int a = 1, int b, int c = 3); // 错!b 没默认值但在 a 后面

// ✅ 正确(从右往左依次有默认值)
void func(int a, int b = 2, int c = 3); // 对

4.3 函数重载

1
2
3
4
5
6
7
8
// 参数个数/类型不同即可重载
int maxVal(int a, int b);
double maxVal(double a, double b);
int maxVal(int a, int b, int c);

// ❌ 只有返回值不同不算重载
int func(int x);
double func(int x); // 错!参数相同只改返回值

4.4 const 参数 vs 非const参数

1
2
3
4
5
6
7
8
9
// 这两个对编译器来说一样(传值拷贝,const 无意义)
void func(int x);
void func(const int x); // 不算重载,报重复定义

// 但引用/指针的 const 有意义:
void func(int& x); // 可修改实参
void func(const int& x); // 只读,可接受常量 ← 重载
func(10); // 调 const& 版本
int a = 5; func(a); // 调非const& 版本

5. 引用:& 的所有用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 1. 引用参数(避免拷贝,可修改实参)
void swap(int& a, int& b) {
int t = a; a = b; b = t;
}

// 2. const 引用参数(只读,可接受常量和变量)
void print(const string& s) { // 不拷贝也不改
cout << s;
}
print("hello"); // ✅ const& 可以接受字面量

// 3. 返回引用(可作左值赋值)
int arr[100];
int& at(int i) {
return arr[i];
}
at(5) = 42; // ✅ 等价于 arr[5] = 42

// 4. const 返回引用(只读)
const string& getName() const {
return name;
}

// 5. 函数返回局部变量的引用 ❌
int& bad() {
int x = 10;
return x; // ❌ 警告/错误!局部变量函数结束销毁
}
// 例外:static 局部变量可以
int& good() {
static int x = 10;
return x; // ✅ static 生命周期到程序结束
}

易错:

1
2
3
4
5
6
7
8
9
// ❌ 非 const 引用接受常量
void func(int& x) {}
func(10); // 错!非const引用不能绑常量

// ❌ 非 const 引用接受临时值
string& ref = string("hi"); // 错!
const string& ref2 = string("hi"); // ✅ const 引用可延长临时值生命周期

// ❌ 返回局部变量引用(见上)

6. 指针:* 的所有用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 1. 指针变量
int x = 10;
int* p = &x; // p 存 x 的地址
cout << *p; // 解引用,输出 10
*p = 20; // 通过指针改 x

// 2. 指针作函数参数(C 风格,C++ 建议用引用代替)
void func(int* p) {
*p = 100;
}
int a = 5;
func(&a); // 传地址

// 3. const 指针
const int* p1; // 指向 const int 的指针:不能通过 p 改值
int* const p2 = &x; // const 指针:不能改 p 指向,但能改值
const int* const p3 = &x; // 都不能改

// 4. 空指针
int* p = nullptr; // C++11 推荐 nullptr,不要用 NULL 或 0
if (p != nullptr) { *p; }

// 5. 动态数组指针
int* arr = new int[100];
arr[0] = 1; // 和数组用法一样
arr[50] = 2;
delete[] arr; // 释放用 delete[] 不是 delete!

// 6. 指向对象的指针
MyClass obj;
MyClass* p = &obj;
p->method(); // 用 -> 访问成员
(*p).method(); // 等价写法

// 7. this 指针(类内部)
class A {
int x;
public:
void setX(int x) { this->x = x; } // 区分参数和成员
A& add(int n) { this->x += n; return *this; } // 返回自身
};

7. 类:完整语法清单

7.1 类的基本结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class ClassName {
private: // 私有(默认就是 private)
int data;
string name;
int* arr; // 指针成员

protected: // 派生类可访问
int protectedData;

public: // 外部可访问
// 构造函数
ClassName();
ClassName(int d);
ClassName(int d, const string& n);

// 析构函数
~ClassName();

// 普通成员函数
int getData() const; // const 成员函数
void setData(int d);

// 静态成员函数
static int getCount();

// 运算符重载
ClassName operator+(const ClassName& rhs) const;
ClassName& operator=(const ClassName& rhs);
int& operator[](int i);
friend ostream& operator<<(ostream& os, const ClassName& obj);
}; // ← 这个分号!!忘了就报错

7.2 成员函数定义(.cpp 中)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include "ClassName.h"

// 普通函数:必须加 ClassName::
int ClassName::getData() const { // const 两边都要有!
return data;
}

void ClassName::setData(int d) {
data = d;
}

// 静态函数:不加 static,但要加 ClassName::
int ClassName::getCount() {
return count; // 只能访问静态成员
}

// 构造函数
ClassName::ClassName() : data(0), name(""), arr(nullptr) {
// 初始化列表后跟函数体
}

ClassName::ClassName(int d) : data(d), name("") {
arr = new int[10];
}

// 析构函数
ClassName::~ClassName() {
delete[] arr; // 有 new 就要 delete
}

易错对比:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// ❌ 类声明后忘了分号
class A {
int x;
} // ← 漏了分号!

// ✅
class A {
int x;
}; // ← 有分号

// ❌ .cpp 中忘了 ClassName::
int getData() const { return data; } // 变成全局函数了

// ✅
int A::getData() const { return data; }

// ❌ 声明有 const,定义忘了
// .h: int getData() const;
// .cpp: int A::getData() { return data; } ← 漏 const!
// 报错:no matching function for call

// ✅ 两边一致
// .cpp: int A::getData() const { return data; }

// ❌ 函数名写错(拼写)
// .h: void setData(int d);
// .cpp: void A::setdata(int d) {} ← d 没大写!
// 报错:undefined reference to 'A::setData(int)'

// ❌ 参数不一致
// .h: void func(const string& s);
// .cpp: void A::func(string s) {} ← 漏了 const 和 &!
// 报错:undefined reference

7.3 访问控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class A {
int x; // 默认 private
private:
int y;
protected:
int z; // 派生类能用,外部不能
public:
int w;
};

struct B {
int x; // struct 默认 public
};

// struct 和 class 唯一区别:默认访问权限

8. 构造函数:所有写法

8.1 初始化列表(强烈推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Student {
int id;
const string name; // const 成员,必须初始化列表
int& score; // 引用成员,必须初始化列表
int* data;
public:
// 初始化列表:成员名(值), 成员名(值)
Student(int id, const string& n, int& s)
: id(id), name(n), score(s), data(nullptr) {
// 函数体可以空,或做其他操作
data = new int[10];
}
};

易错:

1
2
3
4
5
6
7
8
9
10
11
12
13
// ❌ const/引用成员不能用函数体赋值
class A {
const int x;
int& ref;
public:
A(int val, int& r) {
x = val; // 错!const 不能赋值
ref = r; // 错!引用必须初始化
}
};

// ✅ 必须用初始化列表
A(int val, int& r) : x(val), ref(r) {}

8.2 委托构造(C++11)

1
2
3
4
5
6
7
class A {
int x, y;
public:
A() : A(0, 0) {} // 委托给下面的构造函数
A(int x) : A(x, 0) {} // 委托
A(int x, int y) : x(x), y(y) {} // 真正的实现
};

8.3 explicit(禁止隐式转换)

1
2
3
4
5
6
7
class Fraction {
public:
explicit Fraction(int n) : num(n), den(1) {}
};
Fraction f = 5; // ❌ explicit 禁止隐式转换
Fraction f(5); // ✅ 显式构造
Fraction f = Fraction(5); // ✅ 显式

8.4 = delete(禁止拷贝)

1
2
3
4
5
6
class NonCopyable {
public:
NonCopyable() = default;
NonCopyable(const NonCopyable&) = delete; // 禁止拷贝构造
NonCopyable& operator=(const NonCopyable&) = delete; // 禁止赋值
};

8.5 = default(用默认的)

1
2
3
4
5
6
class A {
public:
A() = default; // 用编译器默认生成的
A(const A&) = default;
~A() = default;
};

9. const:所有出现位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 1. const 变量(必须初始化)
const int SIZE = 100;
constexpr int MAX = 1000; // 编译期常量(更强)

// 2. const 引用参数(只读,避免拷贝)
void func(const string& s);
void func(const vector<int>& v);

// 3. const 返回值(少用)
const int& getRef() const;

// 4. const 成员函数(不修改对象状态)
class A {
int x;
public:
int getX() const { return x; } // const 在参数列表后
void setX(int x) { this->x = x; } // 非 const
};

// 5. const 对象只能调 const 函数
const A obj;
obj.getX(); // ✅ const 函数
obj.setX(5); // ❌ const 对象不能调非const函数
// 报错:passing 'const A' as 'this' argument discards qualifiers

// 6. const 成员变量(必须初始化列表)
class A {
const int id;
public:
A(int i) : id(i) {} // ✅
};

// 7. const 指针
const int* p; // 指向的内容不能改
int* const p = &x; // 指针指向不能改

const 一致性规则(高频考点):

1
2
3
4
5
6
7
8
9
10
// 声明和定义的 const 必须完全一致
// .h
int getX() const;
void print() const;
bool empty() const;

// .cpp
int A::getX() const { ... } // ✅ 一致
void A::print() const { ... } // ✅ 一致
// void A::print() { ... } // ❌ 漏 const,链接错误

10. static:成员和函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// .h
class Counter {
private:
int id;
static int count; // 静态数据成员:声明
static const int MAX = 100; // 静态整型常量:可类内初始化
public:
Counter() { id = ++count; }
~Counter() { --count; }
static int getCount(); // 静态成员函数:声明
};

// .cpp
int Counter::count = 0; // ← 必须类外定义一次!忘了就链接错误
int Counter::getCount() { // 定义时不加 static
return count; // 只能访问静态成员,不能用 this
}

易错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ❌ 忘了类外定义静态成员
// .h: static int count;
// 没有 .cpp 中的 int Counter::count = 0;
// 报错:undefined reference to 'Counter::count'

// ❌ 静态函数用了非静态成员
static int getCount() {
return id; // 错!id 是非静态成员
}

// ❌ 静态函数定义时加了 static
// .cpp
static int Counter::getCount() { ... } // 错!定义不能加 static
// ✅
int Counter::getCount() { ... }

11. 动态内存:new/delete 完整写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 1. 单个对象
int* p = new int; // 分配一个 int
int* p = new int(42); // 分配并初始化为 42
int* p = new int(); // 分配并值初始化为 0
delete p; // 释放单个

// 2. 数组
int* arr = new int[100]; // 分配 100 个 int
int* arr = new int[100](); // 全部初始化为 0
arr[0] = 1;
delete[] arr; // ← 数组用 delete[] 不是 delete!

// 3. 二维数组
int** mat = new int*[rows];
for (int i = 0; i < rows; i++)
mat[i] = new int[cols];

// 释放二维数组(顺序反着来)
for (int i = 0; i < rows; i++)
delete[] mat[i]; // 先释放每行
delete[] mat; // 再释放行指针数组

// 4. 对象
MyClass* obj = new MyClass(10);
obj->method();
delete obj;

// 5. 对象数组
MyClass* arr = new MyClass[5]; // 需要默认构造函数!
delete[] arr;

易错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// ❌ new 和 delete 混用
int* arr = new int[100];
delete arr; // 错!应该 delete[]

// ❌ 忘了释放(内存泄漏)
void func() {
int* p = new int(10);
// 忘了 delete p;
} // p 泄漏

// ❌ 释放后继续使用(悬空指针)
int* p = new int(10);
delete p;
*p = 20; // 未定义行为!

// ❌ 二次释放(double free)
int* p = new int(10);
delete p;
delete p; // 崩溃!

// ❌ 浅拷贝导致 double free
class A { int* p; };
A a; A b = a; // 默认浅拷贝,a.p == b.p
// 析构时两个都 delete 同一块内存 → 崩溃
// 解决:写深拷贝三件套

12. 运算符重载:每个运算符的精确写法

12.1 算术运算符(成员函数)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Fraction {
int num, den;
public:
// 返回新对象(不是引用)
Fraction operator+(const Fraction& r) const {
return Fraction(num * r.den + r.num * den, den * r.den);
}
Fraction operator-(const Fraction& r) const { ... }
Fraction operator*(const Fraction& r) const { ... }
Fraction operator/(const Fraction& r) const { ... }

// 复合赋值(返回引用,修改自身)
Fraction& operator+=(const Fraction& r) {
*this = *this + r;
return *this;
}
Fraction& operator-=(const Fraction& r) { ... }
};

12.2 比较运算符(成员函数,返回 bool)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Fraction {
public:
bool operator<(const Fraction& r) const { // 注意 const
return num * r.den < r.num * den;
}
bool operator==(const Fraction& r) const {
return num * r.den == r.num * den;
}
bool operator!=(const Fraction& r) const { return !(*this == r); }
bool operator>(const Fraction& r) const { return r < *this; }
bool operator<=(const Fraction& r) const { return !(r < *this); }
bool operator>=(const Fraction& r) const { return !(*this < r); }
};

12.3 下标运算符(两个版本)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Array {
int* data;
public:
int& operator[](int i) { // 非 const 版:可读可写
return data[i];
}
const int& operator[](int i) const { // const 版:只读
return data[i];
}
};

Array arr;
arr[0] = 10; // 调非 const 版
const Array carr;
int x = carr[0]; // 调 const 版

12.4 自增自减(前置 vs 后置)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Counter {
int val;
public:
// 前置 ++a:返回引用
Counter& operator++() {
++val;
return *this; // 返回自身引用
}

// 后置 a++:int 哑参数区分,返回旧值
Counter operator++(int) { // ← 这个 int 是占位符!
Counter old = *this; // 保存旧值
++val; // 修改
return old; // 返回旧值(副本)
}

// 自减同理
Counter& operator--() { --val; return *this; }
Counter operator--(int) { Counter old = *this; --val; return old; }
};

12.5 流插入/提取(必须友元或类外)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Fraction {
int num, den;
public:
// 类内声明友元
friend ostream& operator<<(ostream& os, const Fraction& f);
friend istream& operator>>(istream& is, Fraction& f);
};

// 类外定义(不加 friend,不加 ClassName::)
ostream& operator<<(ostream& os, const Fraction& f) {
os << f.num << "/" << f.den;
return os; // ← 必须返回 os!否则 cout << a << b 不能连写
}

istream& operator>>(istream& is, Fraction& f) {
is >> f.num >> f.den;
return is;
}

易错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// ❌ << 写成成员函数
class A {
ostream& operator<<(ostream& os) { ... } // 错!左操作数不是 A
};
// cout << a; → 等价于 cout.operator<<(a),但 cout 不是 A

// ✅ 必须友元/类外,左操作数是 ostream
ostream& operator<<(ostream& os, const A& a) { ... }

// ❌ 忘了 return os
ostream& operator<<(ostream& os, const A& a) {
os << a.x; // 没返回
}
// cout << a << b; → 第一个返回 void,第二个报错

// ❌ 后置 ++ 忘了 int 参数
Counter operator++() { ... } // 这是前置!
Counter operator++(int) { ... } // 这才是后置

12.6 函数调用运算符(仿函数)

1
2
3
4
5
6
7
8
9
10
11
12
class Comparator {
bool ascending;
public:
Comparator(bool asc) : ascending(asc) {}
bool operator()(int a, int b) const { // 重载 ()
return ascending ? a < b : a > b;
}
};

Comparator cmp(true);
cout << cmp(3, 5); // 输出 1(true)
sort(arr, arr + n, cmp); // 传给 sort 当比较器

12.7 类型转换运算符

1
2
3
4
5
6
7
8
9
10
11
class Fraction {
int num, den;
public:
// 隐式转换为 double
operator double() const {
return (double)num / den;
}
};

Fraction f(1, 2);
double d = f; // 隐式调用 operator double()

13. 继承:完整语法

13.1 单继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Base {
protected: // 派生类可访问
string name;
public:
Base(const string& n) : name(n) {}
void intro() { cout << name; }
};

// public 继承最常用
class Derived : public Base {
int extra;
public:
// 派生构造:初始化列表先调基类构造
Derived(const string& n, int e) : Base(n), extra(e) {}
// 构造顺序:先 Base → 再 Derived 成员
// 析构顺序:先 Derived → 再 Base(自动)
};

13.2 多重继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class A {
public:
void funcA() {}
};

class B {
public:
void funcB() {}
};

// 逗号分隔
class C : public A, public B {
public:
void funcC() {
funcA(); // 从 A 继承
funcB(); // 从 B 继承
}
};

13.3 继承方式对照

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Base {
public:
int pub;
protected:
int prot;
private:
int priv; // 派生类不可访问
};

class D1 : public Base { // public 继承(最常用)
// pub → public
// prot → protected
// priv → 不可访问
};

class D2 : protected Base { // protected 继承(少用)
// pub → protected
// prot → protected
};

class D3 : private Base { // private 继承(默认,少用)
// pub → private
// prot → private
};

13.4 调用基类成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Base {
public:
void func() { cout << "Base"; }
};

class Derived : public Base {
public:
void func() { cout << "Derived"; } // 隐藏了 Base::func

void test() {
func(); // 调 Derived 的
Base::func(); // 显式调基类的
}
};

14. 虚函数/多态:完整语法

14.1 虚函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Animal {
public:
virtual void speak() const { // virtual
cout << "..." << endl;
}
virtual ~Animal() {} // 虚析构!
};

class Dog : public Animal {
public:
void speak() const override { // override(C++11)
cout << "Woof" << endl;
}
};

// 多态:基类指针/引用调虚函数 → 调实际对象的版本
Animal* a = new Dog();
a->speak(); // 输出 "Woof"(动态绑定)

Animal& ref = *a;
ref.speak(); // 也是 "Woof"

14.2 纯虚函数 / 抽象类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Shape {
public:
virtual double area() const = 0; // = 0 是纯虚函数
virtual void print() const = 0;
virtual ~Shape() {} // 仍然要虚析构
};
// Shape 是抽象类,不能实例化:Shape s; ❌

class Circle : public Shape {
double r;
public:
Circle(double r) : r(r) {}
double area() const override { // 必须实现所有纯虚
return 3.14159 * r * r;
}
void print() const override { // 必须实现
cout << "Circle";
}
};
// Circle 可以实例化

易错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// ❌ 基类析构不是 virtual → delete 基类指针只调基类析构
class Base { ~Base() {} }; // 非 virtual
class Derived : public Base { int* p; ~Derived() { delete p; } };

Base* b = new Derived();
delete b; // 只调 ~Base(),不调 ~Derived() → p 泄漏!

// ✅ 基类析构 virtual
class Base { virtual ~Base() {} };

// ❌ override 签名不一致
class Base { virtual void f(int) const; };
class Derived : public Base {
void f(int) override {} // ❌ 漏了 const,不是 override
// 报错:marked 'override' but does not override
};

// ✅ 签名完全一致
class Derived : public Base {
void f(int) const override {} // 参数、const 都一致
};

// ❌ 抽象类纯虚没全实现
class Base { virtual void a() = 0; virtual void b() = 0; };
class D : public Base {
void a() override {} // 只实现了 a
};
D d; // ❌ 不能实例化,b 还没实现

// ❌ 对象切片(值传递丢失派生部分)
void func(Animal a) { a.speak(); } // 值传递
Dog d;
func(d); // a 是 Animal 副本,调 Animal::speak,不是 Dog

// ✅ 用引用/指针
void func(Animal& a) { a.speak(); }
void func(Animal* a) { a->speak(); }

14.3 final(禁止继承/覆盖)

1
2
3
4
5
6
7
8
// 禁止被继承
class A final { // 不能 class B : public A
};

// 禁止某函数被覆盖
class Base {
virtual void f() final; // 派生类不能覆盖 f
};

14.4 RTTI:typeid 和 dynamic_cast

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <typeinfo>

// typeid:获取类型信息
Animal* a = new Dog();
cout << typeid(*a).name(); // 输出类型名(编译器相关,如 "3Dog")

if (typeid(*a) == typeid(Dog)) {
// 是 Dog 类型
}

// dynamic_cast:向下转型(必须有多态,即基类有 virtual)
Dog* d = dynamic_cast<Dog*>(a);
if (d != nullptr) {
d->bark(); // 安全访问 Dog 特有方法
}

// 引用版本(失败抛异常 bad_cast)
Dog& dr = dynamic_cast<Dog&>(*a);

注意:dynamic_cast 要求基类至少有一个 virtual 函数!

1
2
3
4
5
6
7
8
// ❌ 没有 virtual 不能 dynamic_cast
class Base { int x; };
class Derived : public Base { int y; };

Base* b = new Derived();
Derived* d = dynamic_cast<Derived*>(b);
// 报错:cannot dynamic_cast 'b' (of type 'class Base*') to 'class Derived*'
// (source type is not polymorphic)

15. 模板:完整语法

15.1 函数模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<typename T>            // 或 template<class T>
T myMax(T a, T b) {
return a > b ? a : b;
}

// 使用
cout << myMax(3, 5); // T=int,自动推导
cout << myMax(3.14, 2.71); // T=double
cout << myMax<int>(3, 5); // 显式指定 T

// 多类型参数
template<typename T1, typename T2>
void print(T1 a, T2 b) {
cout << a << " " << b;
}

15.2 类模板(实现必须放 .h/.hpp!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Stack.hpp
#ifndef STACK_HPP
#define STACK_HPP

template<typename T, int N = 100> // N 是非类型参数,可给默认值
class Stack {
private:
T data[N];
int top;
public:
Stack() : top(0) {}
void push(const T& x) { data[top++] = x; }
T pop() { return data[--top]; }
bool empty() const { return top == 0; }
};

#endif

// 使用
Stack<int> s; // T=int, N=100
Stack<double, 50> s2; // T=double, N=50

15.3 类外定义成员(每个都要带 template 前缀)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Stack.hpp
template<typename T>
class Stack {
T data[100];
int top;
public:
void push(const T& x);
T pop();
};

// 类外定义:必须带 template<typename T> 和 Stack<T>::
template<typename T>
void Stack<T>::push(const T& x) {
data[top++] = x;
}

template<typename T>
T Stack<T>::pop() {
return data[--top];
}

易错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// ❌ 模板实现放 .cpp → 链接错误
// Stack.h: template<typename T> class Stack { void push(const T&); };
// Stack.cpp: template<typename T> void Stack<T>::push(const T& x) { ... }
// main.cpp: Stack<int> s; s.push(1);
// 报错:undefined reference to 'Stack<int>::push(int const&)'

// ✅ 模板实现放 .h/.hpp

// ❌ 类外定义忘了 template 前缀
// void Stack<T>::push(const T& x) { ... } ← 漏了 template<typename T>
// 报错:expected ';' before '<' token

// ❌ 类外定义忘了 <T>
// template<typename T>
// void Stack::push(const T& x) { ... } ← 漏了 <T>
// 报错:too few template-parameter-lists

15.4 函数模板全特化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 主模板
template<typename T>
void print(T x) {
cout << "[UNKNOWN] " << x;
}

// 对 int 全特化
template<>
void print<int>(int x) {
cout << "[INT] " << x;
}

// 对 double 全特化
template<>
void print<double>(double x) {
cout << "[DOUBLE] " << x;
}

print(10); // 调 int 特化版
print(3.14); // 调 double 特化版
print("hi"); // 调主模板

15.5 显式实例化

1
2
3
4
5
6
7
8
9
10
11
// 模板只声明在 .h,实现在 .cpp 时,需要在 .cpp 末尾显式实例化
// Stack.h
template<typename T> class Stack { void push(const T&); };

// Stack.cpp
template<typename T>
void Stack<T>::push(const T& x) { /* ... */ }

// 显式实例化(告诉编译器生成这些版本)
template class Stack<int>; // 生成 Stack<int>
template class Stack<double>; // 生成 Stack<double>

16. STL 容器:声明+方法完整表

16.1 vector

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <vector>
vector<int> v;
vector<int> v1(n); // n 个 0
vector<int> v2(n, 5); // n 个 5
vector<int> v3 = {1, 2, 3}; // 初始化列表
vector<vector<int>> mat(n, vector<int>(m, 0)); // 二维

v.push_back(5); // 尾部添加
v.pop_back(); // 尾部删除
v.size(); // 元素个数
v[i]; // 下标访问(不检查越界)
v.at(i); // 下标访问(越界抛异常)
v.front(); // 第一个元素
v.back(); // 最后一个元素
v.empty(); // 是否为空
v.clear(); // 清空
v.begin(); v.end(); // 迭代器
v.insert(v.begin() + i, val); // 在位置 i 插入
v.erase(v.begin() + i); // 删除位置 i
v.resize(n); // 改变大小

// 遍历
for (int i = 0; i < v.size(); i++) cout << v[i];
for (int x : v) cout << x; // 范围 for
for (auto& x : v) x *= 2; // 引用可修改

16.2 string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string>
string s = "hello";
string s2(10, 'a'); // "aaaaaaaaaa"
string s3 = s.substr(1, 3); // "ell"(从位置1取3个字符)
string s4 = s + " world"; // 拼接

s.size(); // 长度(也可 s.length())
s[i]; // 第 i 个字符
s.find("ll"); // 查找子串,返回位置,找不到返回 string::npos
s.find('l'); // 查找字符
s.replace(0, 2, "HI"); // 替换
s.insert(2, "XX"); // 在位置2插入
s.erase(1, 2); // 从位置1删2个字符
s += " world"; // 追加
s.compare(s2); // 比较(<0, 0, >0)
s.c_str(); // 转 C 字符串(const char*)
stoi(s); // string 转 int
stol(s); // string 转 long
stod(s); // string 转 double
to_string(123); // 数字转 string
getline(cin, s); // 读整行(含空格)

16.3 stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stack>
stack<int> stk;
stk.push(1); // 入栈
stk.pop(); // 出栈(无返回值!)
stk.top(); // 栈顶元素
stk.empty(); // 是否为空
stk.size(); // 元素个数
// 注意:stack 没有 clear(),要清空用 while(!stk.empty()) stk.pop();

// 遍历 stack(需借助另一个)
stack<int> temp;
while (!stk.empty()) {
cout << stk.top();
temp.push(stk.top());
stk.pop();
}
while (!temp.empty()) { stk.push(temp.top()); temp.pop(); }

16.4 queue

1
2
3
4
5
6
7
8
#include <queue>
queue<int> q;
q.push(1); // 入队
q.pop(); // 出队(无返回值!)
q.front(); // 队首
q.back(); // 队尾
q.empty();
q.size();

16.5 priority_queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <queue>

// 大顶堆(默认)—— top 是最大值
priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(5);
pq.top(); // 5(最大值)
pq.pop(); // 删除最大值

// 小顶堆—— top 是最小值
priority_queue<int, vector<int>, greater<int>> minpq;
minpq.push(3);
minpq.push(1);
minpq.top(); // 1(最小值)

// 存 pair:默认按 first 比较
priority_queue<pair<int,int>> ppq;
ppq.push({5, 101}); // {severity, id}
ppq.push({3, 102});
ppq.top(); // {5, 101}
ppq.top().first; // 5
ppq.top().second; // 101

16.6 map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <map>
map<string, int> m;
m["tom"] = 90; // 插入/修改
m["tom"]++; // 值自增(不存在自动建0)
m.insert({"jerry", 85}); // 插入
m.count("tom"); // 是否存在(0或1)
m.find("tom"); // 返回迭代器
m.erase("tom"); // 删除
m.size();
m.empty();

// 遍历(按 key 升序!)
for (auto& p : m) {
cout << p.first << ": " << p.second; // key, value
}

// 用迭代器
for (auto it = m.begin(); it != m.end(); ++it) {
cout << it->first << it->second;
}

16.7 set

1
2
3
4
5
6
7
8
9
10
11
#include <set>
set<int> s;
s.insert(3);
s.insert(3); // 重复插入无效
s.count(3); // 是否存在(0或1)
s.find(3); // 返回迭代器
s.erase(3);
s.size();

// 遍历(升序)
for (int x : s) cout << x;

16.8 常用算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <algorithm>
#include <numeric> // accumulate

vector<int> v = {3, 1, 4, 1, 5};

// 排序
sort(v.begin(), v.end()); // 升序
sort(v.rbegin(), v.rend()); // 降序
sort(v.begin(), v.end(), greater<int>()); // 降序
sort(v.begin(), v.end(), less<int>()); // 升序
// 自定义比较器
sort(v.begin(), v.end(), [](int a, int b) {
return a > b; // 降序
});

// 结构体排序
sort(stu.begin(), stu.end(), [](const Student& a, const Student& b) {
if (a.score != b.score) return a.score > b.score; // 分高在前
return a.id < b.id; // 分同 id 小在前
});

// 查找
find(v.begin(), v.end(), 4); // 返回迭代器
count(v.begin(), v.end(), 1); // 计数

// 条件统计
count_if(v.begin(), v.end(), [](int x) { return x > 60; });

// 最大最小
*max_element(v.begin(), v.end()); // 最大值
*min_element(v.begin(), v.end()); // 最小值

// 求和(注意初始值类型!)
int sum = accumulate(v.begin(), v.end(), 0); // int 求和
double avg = accumulate(v.begin(), v.end(), 0.0) / v.size(); // double!

// 反转
reverse(v.begin(), v.end());
reverse(s.begin(), s.end()); // 字符串反转

// 交换
swap(a, b);

17. string:所有常用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <string>
#include <cctype>

// --- 构造 ---
string s1 = "hello";
string s2(5, 'a'); // "aaaaa"
string s3(s1, 1, 3); // "ell"(从位置1取3个)

// --- 长度 ---
s.size(); // 推荐
s.length(); // 同上
s.empty();

// --- 访问 ---
s[0]; // 第一个字符
s.back(); // 最后一个字符
s.front(); // 第一个字符

// --- 查找 ---
s.find("lo"); // 返回位置,找不到 string::npos
s.find('l');
s.rfind('l'); // 从后往前找
// 判断是否找到
if (s.find("xx") != string::npos) { /* 找到了 */ }

// --- 子串 ---
s.substr(2); // 从位置2到末尾
s.substr(0, 3); // 从位置0取3个字符

// --- 修改 ---
s += " world"; // 追加
s.push_back('!'); // 追加一个字符
s.insert(2, "XX"); // 在位置2插入
s.erase(1, 2); // 从位置1删2个
s.replace(0, 2, "HI"); // 替换
s.clear(); // 清空

// --- 比较 ---
s == "hello";
s < "world"; // 字典序比较

// --- 转换 ---
stoi("123"); // → 123
stol("1234567890");
stod("3.14");
to_string(123); // → "123"
s.c_str(); // → const char*

// --- 字符函数(对单个 char)---
char c = 'A';
isalpha(c); // 是否字母
isdigit(c); // 是否数字
isalnum(c); // 是否字母或数字
isspace(c); // 是否空白
isupper(c); // 是否大写
islower(c); // 是否小写
toupper(c); // 转大写(返回值,不改原字符)
tolower(c); // 转小写

// 遍历处理
for (char& c : s) {
c = toupper(c); // 全转大写(用引用改原串)
}

18. IO 格式化:所有操纵符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iomanip>

// --- 小数位数 ---
cout << fixed << setprecision(2) << 3.14159; // 3.14
cout << setprecision(4) << 3.14159; // 3.142(4位有效数字,无 fixed)

// --- 对齐和宽度 ---
cout << left << setw(10) << "Name"; // 左对齐,宽10
cout << right << setw(10) << "Name"; // 右对齐
cout << setw(10) << "Name"; // 默认右对齐

// --- 填充 ---
cout << setfill('0') << setw(5) << 42; // 00042
cout << setfill('*') << setw(5) << "Hi"; // ***Hi

// --- 前导零(时间格式 hh:mm:ss)---
cout << setfill('0') << setw(2) << hour << ":"
<< setfill('0') << setw(2) << minute << ":"
<< setfill('0') << setw(2) << second; // 08:05:09

// --- 进制 ---
cout << dec << 255; // 十进制 255
cout << oct << 255; // 八进制 377
cout << hex << 255; // 十六进制 ff

// --- 前缀 ---
cout << showbase << oct << 255; // 0377(八进制前缀0)
cout << showbase << hex << 255; // 0xff(十六进制前缀0x)
cout << showbase << uppercase << hex << 255; // 0XFF(大写)

// 取消前缀
cout << noshowbase;

// --- 布尔值 ---
cout << boolalpha << true; // true(不是1)
cout << noboolalpha << true; // 1

// --- 显示小数点 ---
cout << showpoint << 3.0; // 3.00000(显示小数点)
cout << noshowpoint << 3.0; // 3

// --- 输入 ---
int x; cin >> x;
string s; cin >> s; // 遇空格停止
getline(cin, s); // 读整行(含空格)
// 注意:cin >> n 后 getline 前要 cin.ignore()
int n; cin >> n;
cin.ignore(); // 吃掉换行符!
getline(cin, s);

// --- 多组输入 ---
while (cin >> x) { ... } // 读到EOF
int n; cin >> n; while (n--) { ... } // 已知组数

IO 操纵符持续性:

1
2
3
4
5
6
7
// 大部分操纵符是持久的(设置后一直生效直到改变)
cout << fixed << setprecision(2); // 后面所有输出都保留2位小数
cout << 3.14159 << endl; // 3.14
cout << 2.71828 << endl; // 2.72

// setw 是一次性的(只影响下一个输出)
cout << setw(10) << "A" << "B"; // A占10位,B正常输出

19. 控制流:易错写法

19.1 switch(记得 break!)

1
2
3
4
5
6
7
8
9
10
11
12
int x;
switch (x) {
case 1:
cout << "one";
break; // ← 不加 break 会穿透到下面!
case 2:
cout << "two";
break;
default:
cout << "other";
break;
}

19.2 范围 for 循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
vector<int> v = {1, 2, 3};

// 只读遍历
for (int x : v) {
cout << x;
}

// 修改元素(必须用引用)
for (int& x : v) {
x *= 2;
}

// 遍历 string
for (char c : s) {
cout << c;
}
for (char& c : s) {
c = toupper(c);
}

// 遍历 map
for (auto& p : m) {
cout << p.first << p.second;
}

19.3 break 和 continue

1
2
3
4
5
6
7
8
9
10
11
12
13
// break:跳出整个循环
for (int i = 0; i < n; i++) {
if (v[i] == target) {
found = true;
break; // 找到就退出
}
}

// continue:跳过本次,继续下一次
for (int i = 0; i < n; i++) {
if (v[i] < 0) continue; // 跳过负数
sum += v[i];
}

20. 类型转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// C 风格转换(能用但不推荐)
int x = (int)3.14;
double d = (double)x;

// C++ 风格转换(推荐)
int x = static_cast<int>(3.14);
double d = static_cast<double>(x);

// 隐式转换
int i = 'A'; // char → int (65)
char c = 65; // int → char ('A')
double d = 10; // int → double (10.0)
int i = 3.14; // double → int (3,截断)

// 安全的整数除法转浮点
int a = 1, b = 3;
double r = (double)a / b; // 0.333...
double r = static_cast<double>(a) / b;

// 字符和数字互转
char c = '5';
int digit = c - '0'; // 5
int n = 7;
char ch = n + '0'; // '7'

// string 和数字
int n = stoi("123");
string s = to_string(456);

21. 编译错误大全:报错→原因→修法

30+ 条常见编译错误速查。

类与成员

报错信息 原因 修法
expected ';' after class definition 或 expected ';' at end of class 类 } 后漏分号 加 };
expected ';' before 某标识符 上一行漏分号 在上一行末加 ;
undefined reference to 'Xxx::func()' 成员函数声明了但没定义 在 .cpp 补 Xxx::func() 定义
undefined reference to 'Xxx::count' 静态成员没类外定义 .cpp 加 int Xxx::count = 0;
no matching function for call to 'Xxx::func()' 函数签名不匹配 检查参数个数/类型/const
cannot declare member function to have static linkage 静态函数定义加了 static 定义时不加 static
'func' is not a member of 'Xxx' 函数名拼错或忘加 Xxx:: 加 Xxx:: 或修正拼写
redefinition of 'Xxx::func()' 函数定义了两次 删除重复定义

const 相关

报错信息 原因 修法
passing 'const Xxx' as 'this' argument discards qualifiers const 对象调了非 const 函数 函数声明加 const
assignment of member 'Xxx::data' in read-only object const 函数里修改了成员 去掉 const 或用 mutable
no matching function for call (const 版) 声明有 const 定义没 const 定义也加 const

include 与作用域

报错信息 原因 修法
'xxx' was not declared in this scope 忘 include / 拼写错 / 没 using namespace 补 include / 检查拼写 / 加 using namespace std;
'cout' was not declared 忘 #include <iostream> 或 using namespace std 补上
'string' was not declared 忘 #include <string> 或 using namespace std 补上
'accumulate' was not declared 忘 #include <numeric> 补上
'sqrt' was not declared 忘 #include <cmath> 补上
'setw' was not declared 忘 #include <iomanip> 补上
redefinition of 'class Xxx' 头文件没保护 / 重复 include 加 #ifndef 或 #pragma once

继承与多态

报错信息 原因 修法
cannot allocate an object of abstract type 'Xxx' 纯虚函数没全实现 派生类实现所有 = 0
marked 'override' but does not override any virtual function 签名不一致 检查参数/const/返回值是否和基类一致
no matching function for call to 'Xxx::Xxx()' 派生类需要默认构造但没提供 加默认构造函数
invalid use of incomplete type 'class Xxx' 两个头文件互相 include 用前向声明 class Xxx;
request for member 'func' is ambiguous 多重继承同名冲突 加 Base::func() 显式指定
cannot dynamic_cast ... (source type is not polymorphic) 基类没有 virtual 函数 基类加至少一个 virtual

模板

报错信息 原因 修法
undefined reference to 'Stack<int>::push(int const&) 模板实现放 .cpp 搬到 .h/.hpp
expected ';' before '<' token 类外定义忘 template<typename T> 加前缀
too few template-parameter-lists 类外定义忘 <T> Stack<T>::func
no matching function for call to 'max(T, T)' 类型不一致 max<int>(3, 3.14) 显式指定
expected primary-expression before '>' token 模板参数不匹配 检查参数类型/个数

运算符重载

报错信息 原因 修法
no match for 'operator<<' 没重载 << 或不是友元 加 friend ostream& operator<<
no match for 'operator<' sort 缺比较 补 operator< 或传 lambda
candidate is: Xxx operator++() 前置后置搞混 后置加 int 哑参数
cannot bind 'std::ostream' lvalue to 'const std::basic_ostream<char>&' << 返回类型错 返回 ostream& 不是 void

运行时错误

现象 原因 修法
Segmentation fault / 段错误 空指针/越界/野指针访问 检查指针和下标
double free / 堆损坏 浅拷贝导致重复释放 补深拷贝三件套
程序卡死无输出 死循环 / 等待输入 检查循环条件和输入
输出后崩 析构时释放已释放内存 检查析构和赋值运算符
结果全 0 忘记读输入 / 初始化 检查 cin 和初始化

链接错误

报错信息 原因 修法
undefined reference to 'WinMain' 没有 main 函数 加 int main()
multiple definition of 'xxx' 全局变量/函数定义在头文件中 只声明在 .h,定义放 .cpp
cannot find -lxxx 缺库 考试一般不会遇到

22. 考前必背 30 条语法口诀

考前最后看一遍这 30 条,能避免 90% 的编译错误。

  1. 类声明后必须有分号:class A { ... }; ← 分号!
  2. 成员函数定义加 ClassName:::int A::getX() const { ... }
  3. const 两边一致:声明和定义的 const 必须完全相同
  4. 默认参数只写声明:.h 写 = 0,.cpp 不写
  5. 静态成员类外定义:int A::count = 0; 不能忘
  6. 静态函数定义不加 static:int A::getCount() { ... }
  7. const/引用成员用初始化列表:A(int x) : id(x), ref(r) {}
  8. new 配 delete,new[] 配 delete[]
  9. 有指针成员写三件套:拷贝构造 + 赋值运算符 + 析构
  10. 赋值运算符 5 步:自检→释放→复制标量→分配→逐个复制→return *this
  11. 基类析构加 virtual:virtual ~Base() {}
  12. override 让编译器检查:void func() override
  13. 抽象类纯虚全实现才能实例化
  14. 多态用指针/引用,值传递会对象切片
  15. dynamic_cast 要有多态(基类至少一个 virtual)
  16. << 重载必须友元,返回 ostream&
  17. 后置 ++ 加 int 哑参数:Counter operator++(int)
  18. 模板实现放 .h/.hpp,不能放 .cpp
  19. 模板类外定义带 template<typename T> 和 <T>
  20. 头文件加保护:#ifndef 或 #pragma once
  21. getline 前要 ignore:cin >> n; cin.ignore(); getline(cin, s);
  22. accumulate 初值 0.0 得 double,0 得 int
  23. priority_queue 小顶堆:priority_queue<int, vector<int>, greater<int>>
  24. map 自动按 key 排序,set 自动去重
  25. 元素间空格末尾不加:if (i+1 < n) cout << " ";
  26. 前导零用 setw+setfill:setfill('0') << setw(2) << 8
  27. stoi/to_string 在 <string> 里
  28. accumulate 在 <numeric> 里(不是 <algorithm>)
  29. toupper/tolower 返回值不改原字符,要 c = toupper(c)
  30. 万能开头一次 include 全:iostream/string/vector/algorithm/queue/stack/map/set/cmath/iomanip/numeric/cctype

使用建议:考前把第 22 节(30 条口诀)背熟,考试中遇到编译错误翻第 21 节对照表,写代码时不确定语法翻对应章节。