用法:考试补充文件时,先看 main.cpp 调用了什么、.h/.hpp 要求什么签名,

再从本手册找对应模块,改类名/成员名直接套。所有代码都按你们课程风格写:

#ifndef 头文件保护 + using namespace std; + 声明(.h)与定义(.cpp)分离。


0. 每题开写前的 4 句自问(防漏条件,30 秒)

  1. main.cpp 到底调用了哪些函数?名字、参数、返回值、const 抄下来。

  2. .h/.hpp 里已经给了哪些成员变量和函数签名?签名一个字都不能改。

  3. 输入有没有:多组数据 / 空串 / 0 / 负数 / 越界 / EOF 结束?

  4. 输出格式:有没有空格、换行、大小写、保留几位小数、排序方向?

记住考试目标:6 题稳过 > 7 题都碰。一题卡 10 分钟不知补什么就跳,卡 20 分钟编译不过就跳。


1. 万能开头(背下来,任何题第一件事)

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

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <queue>

#include <stack>

#include <map>

#include <set>

#include <cmath>

#include <iomanip>   // setprecision / fixed

using namespace std;

分文件规则(补充文件题最常见坑):

  • .h/.hpp 只放声明,最外层永远包一层保护:

1
2
3
4
5
6
7
8
9

  #ifndef XXX_H

  #define XXX_H

  // ... 声明 ...

  #endif

  • .cpp 里 #include "对应的.h",成员函数一律写成 类名::函数名。

  • 模板类是唯一例外:模板的实现要写在 .h/.hpp 里(见第 8 节),不要单独放 .cpp,否则链接错误。


2. 普通类:声明 + 定义分离(周3–周4 基础)

Xxx.h

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

#ifndef XXX_H

#define XXX_H

#include <string>

using namespace std;



class Xxx {

private:

    int a;

    string name;

public:

    Xxx();                          // 默认构造

    Xxx(int a, const string& name); // 带参构造

    int getA() const;               // 读用 const

    void setA(int a);

    void print() const;

};

#endif

Xxx.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include "Xxx.h"

#include <iostream>

using namespace std;



Xxx::Xxx() : a(0), name("") {}                       // 初始化列表

Xxx::Xxx(int a, const string& name) : a(a), name(name) {}

int Xxx::getA() const { return a; }

void Xxx::setA(int a) { this->a = a; }               // 同名用 this->

void Xxx::print() const { cout << a << " " << name << endl; }

易错点清单:

  • 类声明 } 后面必须有分号 };。

  • .cpp 里成员函数必须 Xxx::,忘了就变成全局函数 → 一堆报错。

  • 声明是 const 成员函数,定义也必须带 const,两边要完全一致。

  • 构造优先用初始化列表;const 成员和引用成员只能用初始化列表。


3. 构造/析构/静态成员/常量(周4)

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

class Counter {

private:

    int id;

    static int count;          // 静态成员:声明

    const int level;           // 常量成员:只能初始化列表

public:

    Counter(int lv) : level(lv) { id = ++count; }

    ~Counter() { --count; }    // 析构

    static int getCount();     // 静态函数:不能用 this,只能碰静态成员

};



// .cpp 里:静态成员必须类外定义一次!否则链接错误

int Counter::count = 0;

int Counter::getCount() { return count; }

  • 默认参数只写在声明处:Xxx(int n, int v = 0);,定义处不要再写 = 0。

  • 无参能构造就提供默认构造,main 里 Xxx arr[10]; 才不报错。


4. 动态内存 + 深拷贝三件套(周5–周8,最高频丢分点)

只要类里有 new(成员是指针/动态数组),必须写全下面三个(Rule of Three),否则浅拷贝 → double free / 运行崩。

4.1 动态数组版(IntArray / MyString / Matrix 都是这个骨架)

class.hpp

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

#ifndef CLASS_HPP

#define CLASS_HPP



class IntArray {

private:

    int* data;

    int size;

public:

    IntArray(int n, int initVal = 0);

    IntArray(const IntArray& other);            // 拷贝构造

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

    ~IntArray();                                // 析构

    int& operator[](int i);                     // 下标(可改)

    int  get(int i) const;

    int  getSize() const;

    void print() const;

};

#endif

class.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
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77

#include "class.hpp"

#include <iostream>

using namespace std;



IntArray::IntArray(int n, int initVal) : size(n) {

    data = new int[size];

    for (int i = 0; i < size; ++i) data[i] = initVal;

}



// 拷贝构造:先分配新内存,再逐个复制(深拷贝)

IntArray::IntArray(const IntArray& other) : size(other.size) {

    data = new int[size];

    for (int i = 0; i < size; ++i) data[i] = other.data[i];

}



// 拷贝赋值:固定 5 步,务必背熟

IntArray& IntArray::operator=(const IntArray& other) {

    if (this == &other) return *this;      // 1. 自赋值检查

    delete[] data;                         // 2. 释放旧内存

    size = other.size;                     // 3. 复制标量

    data = new int[size];                  // 4. 分配新内存

    for (int i = 0; i < size; ++i)         // 5. 逐个复制

        data[i] = other.data[i];

    return *this;                          // 别忘 return *this

}



IntArray::~IntArray() { delete[] data; }   // 数组用 delete[]



int& IntArray::operator[](int i) { return data[i]; }

int  IntArray::get(int i) const { return data[i]; }

int  IntArray::getSize() const { return size; }

void IntArray::print() const {

    for (int i = 0; i < size; ++i) {

        cout << data[i];

        if (i + 1 < size) cout << " ";     // 元素间空格,末尾不加

    }

    cout << endl;

}

4.2 “仿 string” 的字符数组版(MyString)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

// 成员: char* str;  int len;

MyString::MyString(const char* s) {

    len = 0; while (s[len] != '\0') ++len;   // strlen

    str = new char[len + 1];                 // +1 放 '\0'

    for (int i = 0; i <= len; ++i) str[i] = s[i];

}

// 拷贝构造 / 赋值 / 析构 同 4.1,注意分配 len+1

4.3 链表版栈(周5 IntStack 链表实现)

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

struct Node { int val; Node* next; };



class IntStack {

private:

    Node* top;

public:

    IntStack() : top(nullptr) {}

    void push(int x) { top = new Node{x, top}; }

    int  pop()  { int v = top->val; Node* p = top; top = top->next; delete p; return v; }

    bool empty() const { return top == nullptr; }

    ~IntStack() { while (top) { Node* p = top; top = top->next; delete p; } }

    // 有指针成员 → 同样要补拷贝构造和赋值(考试若不测拷贝可先跳过,但知道要写)

};

判断要不要写三件套:类里有裸指针 + new → 100% 要写。 只用 vector/string 存数据的类不用写,编译器默认的就够。


5. 运算符重载全家桶(周7 + 周9)

以 Fraction(分数)/ Point 为例,考试改名即可。

5.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
32
33

class Fraction {

    int num, den;

public:

    Fraction operator+(const Fraction& r) const;  // a + b

    Fraction operator-(const Fraction& r) const;

    Fraction operator*(const Fraction& r) const;

    Fraction& operator+=(const Fraction& r);      // a += b,返回引用

};



Fraction Fraction::operator+(const Fraction& r) const {

    return Fraction(num * r.den + r.num * den, den * r.den); // 记得化简

}

Fraction& Fraction::operator+=(const Fraction& r) {

    *this = *this + r;

    return *this;

}

5.2 比较运算符(排序、优先队列都要用)

1
2
3
4
5
6
7

bool operator<(const Fraction& r) 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 r < *this; } // 复用 <

5.3 自增:前置 vs 后置(周7 高频考点)

1
2
3
4
5
6
7
8
9
10
11

Counter& operator++();      // 前置 ++a:先加后返回自身引用

Counter  operator++(int);   // 后置 a++:带 int 占位参数,返回旧值副本



Counter& Counter::operator++()    { ++val; return *this; }

Counter  Counter::operator++(int) { Counter old = *this; ++val; return old; }

5.4 下标运算符(周9 ModBuffer 类)

1
2
3
4
5

int& operator[](int i)             { return data[i]; } // 可读可写

int  operator[](int i) const       { return data[i]; } // const 对象只读

5.5 流插入 <<(必须是友元,写在类外)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

// 类内声明友元:

friend ostream& operator<<(ostream& os, const Fraction& f);

// 类外定义:

ostream& operator<<(ostream& os, const Fraction& f) {

    os << f.num << "/" << f.den;

    return os;   // 返回 os 才能连写 cout << a << b

}

5.6 类型转换 & explicit(周9)

1
2
3
4
5

operator double() const { return (double)num / den; } // 隐式转成 double

explicit Fraction(int n);   // 加 explicit 禁止 int 隐式变 Fraction

运算符重载先确认 成员函数还是友元:左操作数是本类用成员;<</>>、左操作数不是本类,用友元/类外函数。


6. 继承(周10–周11)

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

class Base {

protected:                 // 想让派生类访问 → protected

    string name;

public:

    Base(const string& n) : name(n) {}

    void intro() const { cout << "I am " << name; }

};



class Derived : public Base {   // public 继承最常用

    int extra;

public:

    // 派生类构造:先在初始化列表里调基类构造

    Derived(const string& n, int e) : Base(n), extra(e) {}

};

要点:

  • 派生类构造必须在初始化列表调用基类构造:: Base(参数)。

  • 构造顺序:先基类 → 再派生类成员;析构相反。

  • protected 成员:派生类能用,外部不能。

  • 想调用被隐藏的基类同名函数:Base::func();。


7. 多态 / 虚函数 / 抽象类 / 接口(周12–周14,中高分核心)

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

class Animal {

protected:

    string name;

public:

    Animal(const string& n) : name(n) {}

    virtual void speak() const;      // virtual 才有多态

    virtual ~Animal() {}             // 基类析构必须 virtual!

};



class Dog : public Animal {

public:

    Dog(const string& n) : Animal(n) {}

    void speak() const override { cout << name << ": Woof" << endl; } // override

};

7.2 抽象类 / 纯虚函数 / 接口(周14)

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

class Shape {                        // 抽象类,不能实例化

public:

    virtual double area() const = 0; // 纯虚函数 = 0

    virtual void print() const = 0;

    virtual ~Shape() {}

};



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 area=" << area() << endl; }

};

7.3 基类指针数组统一管理(多态最常见的题型)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Shape* shapes[100];

int n = 0;

shapes[n++] = new Circle(2.0);

shapes[n++] = new Rectangle(3, 4);



for (int i = 0; i < n; ++i)

    shapes[i]->print();          // 自动调各自的实现(动态绑定)



for (int i = 0; i < n; ++i)

    delete shapes[i];            // 因为基类析构是 virtual,才能正确释放

多态题固定自查:

  • 基类析构 virtual 了吗?(漏了 → 内存泄漏 / 扣分)

  • 重写函数签名和基类完全一致吗?(参数、const 差一个都不算重写)→ 加 override 让编译器帮你查。

  • 抽象类的纯虚函数在派生类里全部实现了吗?没实现完 → 派生类还是抽象类,new 会报错。

  • 用基类指针/引用调用才有多态;用对象值调用会“对象切片”,退化成基类。


8. 模板(周15,第6/7题难题常来源)

8.1 函数模板

1
2
3
4
5
6
7
8
9
10
11

template<typename T>

T myMax(T a, T b) { return a > b ? a : b; }



template<typename T>

void mySwap(T& a, T& b) { T t = a; a = b; b = t; }

8.2 类模板(声明和实现都放 .hpp)

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

#ifndef STACK_HPP

#define STACK_HPP



template<typename T>

class Stack {

private:

    T data[100];

    int topIdx;

public:

    Stack() : topIdx(0) {}

    void push(const T& x) { data[topIdx++] = x; }

    T    pop()            { return data[--topIdx]; }

    bool empty() const    { return topIdx == 0; }

};

#endif

若题目坚持声明/实现分离,类外定义要每个函数都带 template<typename T> 前缀:

1
2
3
4
5

template<typename T>

void Stack<T>::push(const T& x) { data[topIdx++] = x; }

8.3 非类型模板参数(周15 RangeFilter / IntervalManager 就是这个)

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

template<typename T, int N>          // N 是编译期常量

class Buffer {

    T data[N];                       // 用 N 定长

public:

    int capacity() const { return N; }

};

// 使用:Buffer<int, 8> b;



// 成员也可以是模板(成员模板):

template<typename T, int N>

template<int Low, int High>

bool Buffer<T,N>::inRange(T v) { return v >= Low && v <= High; }

若 .hpp 里出现 extern template class ...;——那是显式实例化声明,是题目给你的,别删;你只要把成员函数实现补在 .cpp(这种题会配套 template class Xxx<int,2>; 显式实例化),照着给的实例化列表写即可。


9. STL 速查(周16–周17,最快拿分题)

9.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
32
33

vector<int> v;

v.push_back(5); v.size(); v[0]; v.back(); v.pop_back();

for (int x : v) cout << x << " ";              // 范围 for

sort(v.begin(), v.end());                      // 升序

sort(v.rbegin(), v.rend());                    // 降序



string s = "abc";

s.size(); s.substr(1,2); s.find("b"); s += "d";

s[0]; reverse(s.begin(), s.end());



map<string,int> m;

m["tom"] = 90; m["tom"]++;                      // 不存在自动建 0

if (m.count("tom")) ...                          // 查存在

for (auto& p : m) cout << p.first << p.second;   // 按 key 自动升序



set<int> st; st.insert(3); st.count(3); st.erase(3); // 自动去重+有序

9.2 栈 / 队列 / 优先队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

stack<int> stk; stk.push(1); stk.top(); stk.pop(); stk.empty();

queue<int> q;   q.push(1); q.front(); q.pop(); q.empty();



priority_queue<int> pq;                 // 大顶堆,top 最大

priority_queue<int, vector<int>, greater<int>> minpq;  // 小顶堆,top 最小



// 按 pair 排(急诊分诊:severity 大优先,pair 默认先比 first)

priority_queue<pair<int,int>> er;       // {severity, id}

er.push({5, 101});

auto t = er.top(); er.pop();            // t.first=优先级 t.second=id

9.3 算法 + lambda(周17 回调/排序核心)

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

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 小在前

});



int c = count_if(v.begin(), v.end(), [](int x){ return x > 60; });

int sum = accumulate(v.begin(), v.end(), 0);           // #include <numeric>

auto it = find(v.begin(), v.end(), 5);

auto mx = *max_element(v.begin(), v.end());

9.4 迭代器

1
2
3
4
5

for (auto it = v.begin(); it != v.end(); ++it) cout << *it;

v.erase(v.begin() + 2);                 // 删第 3 个


10. 输入输出套路(读题必备)

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

// 1) 读到文件末尾 EOF(最常见)

int x;

while (cin >> x) { /* 处理 x */ }



// 2) 已知组数

int n; cin >> n;

while (n--) { /* ... */ }



// 3) 整行读取(含空格)——先吃掉换行

int k; cin >> k; cin.ignore();

string line; getline(cin, line);



// 4) 按命令字符串分发(模拟题常见)

string cmd;

while (cin >> cmd) {

    if (cmd == "push") { int v; cin >> v; /*...*/ }

    else if (cmd == "pop") { /*...*/ }

    else if (cmd == "end") break;

}



// 5) 保留小数

cout << fixed << setprecision(2) << 3.14159 << endl;  // 3.14



// 6) 布尔按 true/false 输出

cout << boolalpha << (a < b) << endl;


11. 字符串常用招式(周2)

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

// 判回文

bool isPal(const string& s){

    int i=0,j=s.size()-1;

    while(i<j) if(s[i++]!=s[j--]) return false;

    return true;

}

// 大小写

#include <cctype>

toupper(c); tolower(c); isalpha(c); isdigit(c);

// 数字字符 <-> 数值

int d = c - '0';          char c = d + '0';

// 字符串 <-> 数字

int n = stoi("123");      string s = to_string(456);

// 分割 / 统计:逐字符扫一遍,遇分隔符切段


12. 高频编译错误 → 秒修对照表

| 报错现象 | 原因 | 修法 |

|—|—|—|

| expected ';' after class definition | 类 } 后漏分号 | 加 }; |

| undefined reference to 'Xxx::f()' | 成员函数没定义 / 静态成员没类外定义 / 模板实现放了 .cpp | 补定义;模板实现搬进 .h |

| 'xxx' was not declared | 忘 include / 拼写错 / 忘 using namespace std | 补头文件 |

| passing 'const Xxx' as this discards qualifiers | const 对象调了非 const 函数 | 给读取类函数加 const |

| no match for 'operator<' | sort/优先队列缺比较 | 补 operator< 或传 lambda |

| cannot allocate abstract type | 抽象类纯虚没实现全 | 派生类实现所有 =0 函数 |

| invalid use of incomplete type | 头文件互相 include | 用前向声明 class X; |

| 运行崩 / double free | 浅拷贝 | 补深拷贝三件套(第4节) |


13. 考场 180 分钟节奏(贴墙上)

| 时间 | 动作 |

|—|—|

| 0–5min | 扫 7 题,每题标 A(会)/B(可能)/C(时间杀手),定顺序 |

| 5–65min | 先做 3 道 A:字符串/基础类/STL |

| 65–125min | 2 道中等:深拷贝 / 多态 / 优先队列 |

| 125–160min | 第 6 题:模板或较熟的模拟题 |

| 160–175min | 回收一个半成品,至少让它编译过 + 过样例 1 |

| 175–180min | 全部重编译,确认没漏交文件 |

跳题红线:读完 5 分钟不知补什么 → 跳;写 15 分钟全红 → 跳;要推倒重写 → 先交能编译版本,最后回来。目标是 6 题有效提交,不是 7 题完美。


附:每种题型“认脸”速查

| 看到这些关键词 | 用哪节模板 |

|—|—|

| 分数/复数/坐标/时间 + + - * < == | 第 5 节 运算符重载 |

| int* / char*、new、深拷贝、MyString、Matrix | 第 4 节 三件套 |

| virtual、基类指针数组、Shape/Animal/Vehicle | 第 7 节 多态 |

| = 0、抽象、接口、device/cargo | 第 7.2 抽象类 |

| template、<T>、<T, N>、Filter/Manager | 第 8 节 模板 |

| 优先队列、排队、分诊、Top-K、括号匹配 | 第 9 节 STL |

| 命令 push/pop/query 循环 | 第 10 节 命令分发 |