double sum(double a, double b) {
return a + b;
}
double mean(double a, double b) {
return sum(a, b) / 2.0;
}
int main() {
double result = mean(2.0, 5.0);
return 0;
}
共同旧版本只有 int main() {}。Alice 在它前面加 sum,Bob 也从这个旧版本开始,在同一空档加 multiply。Git 比较共同祖先和两边的新文本,可能无法自动决定插入结果。
<<<<<<< HEAD
double sum(double a, double b) { return a + b; }
=======
double multiply(double a, double b) { return a * b; }
>>>>>>> multiply-divide
int main() {}
在这次普通 merge 中,Current / HEAD 是当前分支,Incoming 是正在合入的分支。上下顺序取决于合并方向。你需要两个函数,就删除标记,保留两段函数和一个 main。
先切回 main,再创建 multiply-divide。这样 Bob 从共同起点开始写乘除。放在 main 外并提交。
#include <stdexcept>
double multiply(double a, double b) { return a * b; }
double divide(double a, double b) {
if (b == 0.0) {
throw std::invalid_argument("Cannot divide by zero");
}
return a / b;
}
int main() { return 0; }
应用:元素下标和容器长度通常用 std::size_t。空 vector 上不要先算 size()-1;长度为零时会发生无符号下溢。大矩阵的 int 乘加也可能溢出,示例只使用小整数。
6 · auto 推导类型;const 防止意外修改
auto a = 5 / 2; // int,值为 2
auto b = 5.0 / 2; // double,值为 2.5
const double pi{3.141592653589793};
// pi = 3.0; // 编译错误
const auto n = 195; // const int
auto 让编译器从初始化表达式推导类型,不会自动挑选“最精确”的类型;5/2 已经是整数运算。const 表示初始化后不能通过这个名字修改对象。
std::vector<int> v{1, 2, 3};
for (auto x : v) x *= 2; // v 仍是 [1,2,3]
for (auto& x : v) x *= 2; // v 变成 [2,4,6]
for (const auto& x : v) {
std::cout << x << ' '; // 只读,不复制元素
}
第一种每轮拿到一个副本 x,改副本不影响 v。第二种 x 是当前元素的别名,改 x 就是改原元素。第三种也是别名,但通过它不能修改元素。这里的 & 是引用,不是取地址操作。
应用:Tutorial 的 populate_vector 要真正写入病例数据,所以用 auto&。只打印一行矩阵时用 const auto&,既不复制整行,也防止误改。需要同时访问国家名和病例数时,用带下标的传统 for 循环更直观。
11 · 从一组数变成矩阵:A[i][j] 是第几行第几列?
std::vector<int> v{2, -1};
std::vector<std::vector<int>> A{{1, 2}, {3, 4}};
std::vector<int> m(2, 0);
for (std::size_t i = 0; i < 2; ++i)
for (std::size_t j = 0; j < 2; ++j)
m[i] += A[i][j] * v[j];
// m = [0, 2]
执行次序
正在计算
更新后的结果
i=0,j=0
m[0] += 1×2
m[0]=2
i=0,j=1
m[0] += 2×(-1)
m[0]=0
i=1,j=0
m[1] += 3×2
m[1]=6
i=1,j=1
m[1] += 4×(-1)
m[1]=2
每一行与 v 做一次点积,得到结果向量中的一个数。i 选行和输出位置,j 遍历这一行的列以及 v 的元素。m 必须先清零;循环里用 += 累加,写 = 会覆盖前一项。
#include <iostream>
int offset(int); // 声明,参数名可以省略
int main() {
int a = 2;
int b = offset(a); // 调用,a 是 argument
std::cout << a << ' ' << b << '\n';
}
int offset(int x) { // 定义,x 是 parameter
int y = x + 40;
return y;
}
While step is running, which variables are still waiting to finish initialization?
显示中文翻译
当 step 正在运行时,哪个变量还没有完成初始化?
查看解析
offset 的 y 正等 step 返回,main 的 b 又在等 offset 返回。
传值、引用与常量引用
讲义 PDF 第 9–13 页
参数写法
调用后原对象
典型用途
T x
普通左值实参用于初始化独立参数。修改这个参数的值不会改写原对象。
int、double 等容易复制的输入,或函数需要自己的副本。
T& x
x 是原对象的别名,可通过它修改原对象。
初始化矩阵、就地更新数据。需要可修改的左值。
const T& x
通过这个引用只读访问。传入类型匹配的现有对象时,无需复制一份对象。
打印、求和、矩阵乘法的只读输入。也可以绑定常量和临时值。
int shifted(int x) {
x += 40;
return x;
}
void shift_in_place(int& x) {
x += 40;
}
int a = 2;
int b = shifted(a); // a == 2, b == 42
shift_in_place(a); // a == 42,调用时仍写 a
// 错误示例,仅用于读代码
int& bad_offset(int x) {
int y = x + 40;
return y; // y 已无法在函数返回后访问
}
// 按值返回计算结果
int offset_value(int x) {
return x + 40;
}
// 前提:调用方的 a 比返回引用活得久。
int& identity(int& a) {
return a;
}
若 int& r = identity(a);,给 r 赋值会修改 a。若直接写 int r = identity(a);,则读取 a 的值来初始化独立的 r。把 bad_offset 的返回语句改成 return x; 仍然会返回悬空引用,因为该版本的 x 是按值形参。
Implement Euclid’s algorithm once with recursion and once with a loop. Keep the two integer parameters and integer return type. Local temporary variables are allowed. Do not use static or global variables. For the optional variant, use a loop without declaring a temporary variable yourself.
先处理 b == 0,这样才不会算 a % 0。以 gcd(48,18) 为例,第二个参数依次变成 18、12、6、0,最终返回 6。以下示例按非负输入讲解。
int gcd_recursive(int a, int b) {
if (b == 0) return a;
return gcd_recursive(b, a % b);
}
int gcd_iterative(int a, int b) {
while (b != 0) {
const int remainder = a % b;
a = b;
b = remainder;
}
return a;
}
每次转换都保留公约数。若 a = q × b + r,能同时整除 a 和 b 的数也能整除 r = a − q × b,反过来也成立。因此最后可以直接取 b == 0 时的 a。
循环中要在改写 a 之前保存余数。若先写 a = b,再写 b = a % b,用到的就是更新后的 a,余数会立刻变成 0。swap 版先把 a 变成余数,再交换两个值,得到同样的下一状态。
示例的约定是非负整数。如果提供 (0,0),实现返回 0。要支持负数,应先明确结果符号和取值范围,尤其是 int 的最小值取绝对值可能不可表示。
完整 C++17 示例 · 三种 GCD 写法
#include <iostream>
#include <utility>
int gcd_recursive(int a, int b) {
if (b == 0) return a;
return gcd_recursive(b, a % b);
}
int gcd_iterative(int a, int b) {
while (b != 0) {
const int remainder = a % b;
a = b;
b = remainder;
}
return a;
}
int gcd_with_swap(int a, int b) {
while (b != 0) {
a %= b;
std::swap(a, b);
}
return a;
}
int main() {
std::cout << gcd_recursive(48, 18) << '\n';
std::cout << gcd_iterative(48, 18) << '\n';
std::cout << gcd_with_swap(48, 18) << '\n';
}
运行会逐行输出三个 6。
E2 · Overloading Operators
Starting with the previous worksheet’s matvec.cpp, overload the printing functions for int and double. Overload operator* for a double matrix and vector. Write bool test_matrix_vector_product() to compare with a reference result. Report whether the test passed and print both vectors if it failed. The optional extensions are integer multiplication and a unit-testing framework.
显示中文翻译
接着上章的 matvec.cpp,为 int 和 double 重载向量与矩阵的打印函数。重载 operator*,让双精度矩阵和向量能直接用 A * v 相乘。编写 bool test_matrix_vector_product(),将实际结果和参考结果比较,报告通过或失败,失败时打印两个向量。可选部分是支持整数版乘法,以及用单元测试框架写同样的测试。
第 1 步 · 重载打印
保留原来的两个整数版函数,再各定义一个同名的双精度版本。矩阵打印可以遍历各行,并重用向量打印。
void print_vector(const std::vector<double>& v) {
for (double x : v) std::cout << x << ' ';
std::cout << '\n';
}
void print_matrix(const std::vector<std::vector<double>>& A) {
for (const auto& row : A) print_vector(row);
}
Write two print_vector overloads, one for std::vector<int> and one for std::vector<double>. Print one element per line. Each function should read the input without copying the vector or modifying its elements.
void print_vector(const std::vector<int>& v) {
for (int x : v) std::cout << x << '\n';
}
void print_vector(const std::vector<double>& v) {
for (double x : v) std::cout << x << '\n';
}
两版参数类型不同。循环会逐个复制很小的数值,整个向量通过常量引用传入。
3. Multiply a rectangular matrix
对应 W03 E2.2 · 行列与循环边界
Let A = {{2, 1}, {0, 3}, {-1, 4}} and v = {3, -2}. Compute A * v by hand. Give the output length and the exclusive upper bounds for the row and column loops.
显示中文翻译
给定 A = {{2, 1}, {0, 3}, {-1, 4}} 和 v = {3, -2},手算 A * v。写出结果长度,并给出行循环和列循环的上界,也就是 i < ? 和 j < ?。
查看答案
输出 [4, -6, -11]。三行各产生一个结果,外层是 i < A.size()(3),内层是 j < v.size()(2)。
4. Catch a bug with a test
对应 W03 E2.3 · 测试用例设计
A faulty implementation uses result[i] = A[i][j] * v[j] in the inner loop. Give a matrix, a vector, the correct output and the faulty output for a test that catches this bug. Explain why your test works.
int cases = 12;
int other = 30;
int* p = &cases; // 声明指针,&cases 取地址
int& r = cases; // 声明引用,让 r 成为 cases 的别名
*p = 20; // 解引用,修改 cases
p = &other; // p 现在指向 other
r = 25; // r 仍然指向原对象,cases 变成 25
p 存地址,*p 访问那个地址上的对象。指针可以改指向,也可以是 nullptr。引用要在声明时绑定,给引用赋值会修改它引用的对象。访问指针前要确认它指向一个仍然活着的对象,非空检查只排除了空指针。
const int* p 允许改指向,通过它只能读。int* const p 固定指向,可以改 *p。两个位置都写 const 时,这两种修改都受限制。
A program allocates A = new double*[3] and then allocates each row with new double[2]. It ends with only delete[] A. Identify the allocations that leak and write the cleanup code.
for (std::size_t i = 0; i < 3; ++i) {
delete[] A[i];
}
delete[] A;
2. Find the owner
对应 W04 E2 · 独占所有权
Given auto p = std::make_unique<int>(7); int* view = p.get(); auto q = std::move(p);, who owns the integer? Can you read *view immediately after the move? What changes after q.reset()?
Compute the cases per 100,000 people for 75 cases and a population of 30000. Explain why (cases / population) * 100000.0 gives the wrong value when both inputs are integers, and propose a test for zero population.
You save auto it = v.begin(), then call v.push_back(9). Assume the vector reallocates. Can you use *it? How do you read the first element safely afterward?
#include <array>
constexpr int square(int x) { return x * x; }
constexpr int n = square(3);
static_assert(n == 9);
std::array<int, n> values{};
int input = 0;
std::cin >> input; // 此段放在 main 中,并包含 <iostream>
const int a = input; // 只读,值来自运行期
int b = square(input); // 合法的运行期调用
// constexpr int c = input; // 错:input 不是常量表达式
自检:constexpr int f(int x) 后面能接用户输入再调用吗?
查看解释
可以。调用结果未被要求为常量表达式时,constexpr 函数同样可在运行期使用。
8. 宏与条件编译
#define 是预处理文本替换,没有 C++ 类型检查。表达式宏要格外小心括号和重复求值。对于计算常量和小函数,通常优先 constexpr;宏仍适用于 include guards 和条件编译。
Q1 · Which stage resolves a call to a function defined in another object file?
显示中文翻译
哪一个阶段解析另一个目标文件中的函数调用?
Q2 · main.cpp includes helper.h. Where should the ordinary non-inline function body normally be?
显示中文翻译
普通非 inline 函数的函数体通常应放在哪里?
Q3 · What do include guards prevent?
显示中文翻译
Include guards 防止什么?
Q4 · Which statement about constexpr functions is correct?
显示中文翻译
关于 constexpr 函数,哪项正确?
Q5 · Only helper.cpp changes. With correct dependencies, what is rebuilt?
显示中文翻译
只修改 helper.cpp,依赖完整时重建哪些部分?
Q6 · Both main.o and helper.o depend on helper.h. That header changes. What happens?
显示中文翻译
两个目标文件都依赖 helper.h,修改它后会怎样?
Q7 · Which option helps the compiler find Eigen/Dense?
显示中文翻译
哪个选项帮助编译器找到 Eigen/Dense?
Q8 · CMake configuration succeeded. What is the next build command?
显示中文翻译
CMake 配置成功后,使用哪个命令构建?
Q9 · Why use target_link_libraries(app PRIVATE Eigen3::Eigen) for a header-only library?
显示中文翻译
header-only 库为什么也使用 target_link_libraries?
Q10 · For a 2-by-3 matrix A and a vector x of length 3, what is the length of A*x?
显示中文翻译
2×3 矩阵乘长度 3 的列向量,输出长度是多少?
Q11 · What does add_test do?
显示中文翻译
add_test 做什么?
Q12 · Why is auto result = A*x sometimes different from Eigen::VectorXd result = A*x?
显示中文翻译
为什么这两种声明有时不一样?
Q13 · Split and repair a three-file project. Explain an undefined symbol, a repeated default argument and a duplicated definition. Write its build command.
显示中文翻译
把 mean 函数拆为 main.cpp、helper.h、helper.cpp,解释漏编实现、重复默认实参、头文件重复普通定义三种问题,并写构建命令。
你已经使用过面向对象:std::vector<int> v{1,2}; 中,vector<int> 是类型,v 是这个类型的一个对象。v.size() 是对 v 调用成员函数;v 内部保存数据,也保存长度等状态。
类(class)把数据和操作这些数据的行为放在一起。对象(object)是按这个类型创建的具体实例。下面 a、b 类型相同,但各有自己的坐标;修改 a 不会自动改 b。类定义结尾的分号不可漏。
class Point {
public:
double x{0.0};
double y{0.0};
void scale(double k) { x *= k; y *= k; }
};
Point a{2.0, 3.0};
Point b{4.0, 5.0};
a.scale(2.0); // a=(4,6), b=(4,5)
自检:Point 是变量吗?a.scale(2) 修改谁?
展开解释
Point 是类型;a 和 b 才是对象。调用对象是 a,所以 scale 中的 x、y 属于 a。
OOP 1 讲义 PDF p.5–8 · 页码包含讲义备注页
2. public / private 与封装
public 是外部可以使用的接口;private 是类内部的实现。封装(encapsulation)让对象维护自己的规则,例如电池电量必须在 0 到 100 之间。把变量改为 private 后,再提供会检查条件的操作,才能保护规则。
private 按“类”授权:同一个类的成员函数可以访问另一个同类对象的 private 成员。struct 和 class 都能有函数、构造和 private;主要语法差异是默认成员访问及默认基类访问分别为 public 与 private。
class Battery {
int percent_{50}; // class 默认 private
public:
void set_percent(int value) {
if (value < 0 || value > 100)
throw std::invalid_argument("percent");
percent_ = value;
}
int percent() const { return percent_; }
};
// 需要 #include <stdexcept>
Battery b;
b.set_percent(80);
// b.percent_ = -10; // 编译错误:private
class Point {
public:
double x, y;
Point(double a, double b) : x{a}, y{b} {}
};
class Line {
std::array<Point, 2> vertices_;
public:
Line(Point a, Point b) : vertices_{a, b} {}
};
// 需要 #include <array>
Line edge{Point{0,0}, Point{3,4}};
T b = a; 在声明 b,因此是拷贝初始化,通常调用拷贝构造。b = a; 中 b 已存在,调用赋值运算符。函数按值接收已有左值也可能拷贝;返回临时对象时可能省略拷贝,不能机械地按语法数次数。
class Point {
public:
double x{0}, y{0};
Point() = default;
Point(const Point& other) : x{other.x}, y{other.y} {}
Point& operator=(const Point& other) {
x = other.x; y = other.y;
return *this;
}
};
Point a;
Point b{a}; // 创建 b:拷贝构造
Point c = a; // 创建 c:仍是拷贝构造
b = a; // b 已存在:拷贝赋值
自检:Point c = a; 为什么不是调用 operator=?
展开解释
这行声明并创建 c。operator= 需要左侧已经存在的对象;此时 c 正在被创建。
OOP 1 讲义 PDF p.21–24、38–41 · 页码包含讲义备注页
10. 状态和身份:Person 为什么不能照抄 ID?
状态(state)是坐标、健康状况等;身份(identity)是用来区分对象的 ID。W06 明确规定每个 Person 有独立、终身不变的 ID,因此不能完全使用逐成员默认拷贝。
拷贝构造创建新 Person:复制状态,发新 ID。赋值操作改变已有 Person 的状态:保留左侧自己的 ID,不增加计数。一般类如何定义“相等”或“复制”由业务规则决定,不是每种类都必须这样设计。
// 假设 counter 从 0 开始且无其他 Person 被创建
Person a{std::array<double,2>{0,0}}; // id=0
Person b{a}; // id=1,状态与 a 相同
Person c{std::array<double,2>{2,3}}; // id=2
a = c; // a 的位置变为 (2,3),a.id 仍为 0
// counter 仍为 3;赋值没有创建新人
自检:a=c 后 a 和 c 是同一个对象吗?
展开解释
不是。两个对象仍有各自地址和 ID,只是赋值后指定的状态相同。
OOP 1 讲义 PDF p.42、44;W06 p.1–2 · 页码包含讲义备注页
11. enum class 和 static 共享计数器
enum class 定义一组有名字的离散状态。Status::Healthy 比裸整数 0 更能表达含义,且不会随意隐式转换成 int。