1. 类型与变量
初学最容易忽略两件事:一是类型精度,二是常量约束。`const` 用得越早,后面越不容易写出“被意外修改”的 bug。
#include <iostream>
using namespace std;
int main() {
int count = 42;
double price = 19.9;
char grade = 'A';
bool ok = true;
const int max_size = 100;
cout << count << ", " << price << ", "
<< grade << ", " << ok << endl;
return 0;
}
经验:需要表达“不会变”的值,就直接 `const`,不要等后期重构再补。
2. 分支与循环
循环写法上,`for (int i = 0; i < n; ++i)` 是最稳妥基线。边界条件写错 1 位,可能直接数组越界。
for (int i = 0; i < 5; ++i) {
if (i % 2 == 0) {
cout << i << " is even" << endl;
} else {
cout << i << " is odd" << endl;
}
}
高频错误:把 `<` 写成 `<=`,尤其在遍历容器时非常危险。
3. 函数与参数传递
函数是把复杂逻辑拆小的第一步。实践中建议默认优先 `const T&`,减少不必要复制,提高性能与可读性。
int add(int a, int b) {
return a + b;
}
void show_name(const string& name) {
cout << name << endl;
}
4. 指针与引用
引用适合“必须绑定、语义清晰”的场景;指针适合“可空、可重定向”的场景。能不用裸指针时,优先不用。
int x = 10;
int* p = &x; // 指针
int& r = x; // 引用
*p = 20;
r = 30;
cout << x << endl; // 30
不要解引用空指针;这是线上崩溃的经典来源。
5. 类与对象
类是把“数据 + 行为”打包在一起。先把封装和构造函数写清楚,再考虑继承与多态。
class Student {
private:
string name;
int age;
public:
Student(string n, int a) : name(n), age(a) {}
void print() const {
cout << name << ", " << age << endl;
}
};
成员函数不修改对象状态时,记得加 `const`,这是一种自解释约束。
6. STL 容器与算法
写业务代码时,`vector + algorithm` 已经能覆盖大部分需求。先学会“用标准库”,再考虑手写数据结构。
#include <vector>
#include <algorithm>
vector<int> nums = {5, 2, 8, 1};
sort(nums.begin(), nums.end());
for (int v : nums) {
cout << v << " ";
}
7. 常见坑与调试方法
我自己最常踩的三个坑
1) 下标越界:循环边界和容器大小不匹配。
2) 未初始化变量:局部变量默认不清零,结果完全随机。
3) 头文件循环依赖:编译报错又长又难看,优先前置声明再拆文件。
调试习惯
编译时打开警告,保持“每个 warning 都要解释”。把调试当作写代码的一部分,不是最后补救步骤。