函数与重载
理解参数传递方式、重载决议与函数指针的用法
#声明与定义分离
上一章提到了头文件放声明、源文件放实现,这一节把它的价值讲透。C++ 里声明(declaration)告诉编译器"有这么个东西,长这样",定义(definition)才真正给出实体(函数体、变量存储空间)。函数可以被声明多次,但只能被定义一次——这条规则叫 ODR(One Definition Rule)。
这么做有两个实际收益:一是编译顺序不再受限,main 可以写在 helper 前面,只要前面有声明;二是减少重编译,改一个函数体只需重编译那一个 .cpp。Python 和 JS 里函数必须先定义后调用(顶层脚本按顺序执行),Java 靠整个编译单元统一解析所以没这个限制,C++ 则用"先声明后使用"手工解决。
#include <iostream>
#include <string>
// —— 声明区:只有签名,没有函数体 ——
int add(int a, int b); // 函数声明
void greet(const std::string& name); // 参数用 const 引用,避免复制
int get_answer(); // 无参函数
// —— main 可以放在实现之前,因为编译器已经从声明知道了签名 ——
int main() {
std::cout << add(2, 3) << "\n";
greet("Qt");
std::cout << get_answer() << "\n";
return 0;
}
// —— 定义区:真正给出函数体 ——
int add(int a, int b) {
return a + b;
}
void greet(const std::string& name) {
std::cout << "你好," << name << "!\n";
}
int get_answer() {
return 42;
}注意签名必须完全一致:返回类型、函数名、参数类型列表三者共同构成签名。只改返回类型不构成重载,会报"重定义"错误。
#参数传递:值、引用、const 引用、指针
这是 C++ 和其他语言差异最大的地方之一,务必彻底搞清。
Java 只有一种传参方式:值传递。传基本类型时复制数值,传对象时复制的是"引用的副本"——所以 void f(List l) { l = new ArrayList(); } 不会影响调用方的变量,但 l.add(x) 会影响同一个对象。Python 和 JS 也是这个模型(常被叫做"对象引用按值传递")。
C++ 给了你四个明确选项:
- 按值
T:复制一份。安全但有拷贝成本,适合int、double这类小类型。 - 按引用
T&:不复制,函数内修改会影响调用方。用作输出参数。 - 按 const 引用
const T&:不复制,且承诺不修改。这是大对象(如std::string、std::vector)传参的默认选择。 - 按指针
T*:不复制,可传nullptr表示"可选/无"。修改*p会影响调用方。
#include <iostream>
#include <string>
#include <vector>
struct Big {
std::string name;
std::vector<int> data;
};
// 1) 按值:复制一份,函数内怎么改都不影响外面
void by_value(int n) {
n += 100;
}
// 2) 按引用:直接操作调用方的变量
void by_ref(int& n) {
n += 100;
}
// 3) 按 const 引用:零拷贝且只读,传递 std::string / std::vector 的首选
// 对比 Java:参数其实传的是引用副本,对象内容仍可被改;C++ 的 const 是硬约束
void print_all(const Big& b) {
std::cout << b.name << " 有 " << b.data.size() << " 个元素\n";
// b.name = "x"; // 编译错误:const 引用不允许写入
}
// 4) 按指针:语义是"可选参数",nullptr 表示没有
void try_update(int* n) {
if (n == nullptr) {
std::cout << "没有传入指针,跳过\n";
return;
}
*n += 100;
}
// 多返回值:C++ 没有 Python 的元组解包返回,常用引用做输出参数
// (更好的做法是用 struct 或 std::pair/std::tuple 返回,见第 7 章)
bool divide(int a, int b, int& quotient, int& remainder) {
if (b == 0) {
return false; // 用返回值表达成功/失败,常见于 C++17(无 std::optional 前的习惯)
}
quotient = a / b;
remainder = a % b;
return true;
}
int main() {
int x = 1;
by_value(x);
std::cout << "按值后 x = " << x << "\n"; // 1,没变
by_ref(x);
std::cout << "按引用后 x = " << x << "\n"; // 101,变了
try_update(&x);
std::cout << "按指针后 x = " << x << "\n"; // 201
try_update(nullptr); // 优雅处理空值
Big b{"dataset", std::vector<int>{1, 2, 3}};
print_all(b);
int q = 0, r = 0;
if (divide(17, 5, q, r)) {
std::cout << "17 / 5 = " << q << " 余 " << r << "\n";
}
return 0;
}选择口诀:小类型(≤ 指针大小)按值,大类型按 const 引用,要修改按引用,可空按指针。这条规则会贯穿整本教程。
#默认参数与函数重载
默认参数和 Python/JS 的写法几乎一致:void log(const std::string& msg, int level = 1)。两点 C++ 特有的规矩:默认参数只能出现在参数列表的尾部;且只在声明处写一次,如果在头文件写了又在 .cpp 定义处再写一遍,会被当成重复定义而报错。
函数重载允许同名函数共存,只要参数列表(类型、个数、顺序)不同。编译器根据实参做"重载决议"(overload resolution)。这一点和 Java 的方法重载几乎一样;而 Python 和 JS 没有真正的重载——Python 靠 *args 和默认值模拟,JS 后定义的同名函数会直接覆盖前面的。
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
// 重载组 1:按参数个数重载(这两个都没有默认值,决议清晰)
void log_info(const std::string& msg) {
std::cout << "[INFO] " << msg << "\n";
}
void log_info(const std::string& msg, int level);
// 默认参数单独用一个函数演示:默认值只写在声明处,且必须位于参数列表尾部
void connect(const std::string& host, int port = 80, int timeout_ms = 3000);
// 重载组 2:按参数类型重载
int max_of(int a, int b) {
return a > b ? a : b;
}
double max_of(double a, double b) {
return a > b ? a : b;
}
// 重载组 3:按不同类型重载
void inspect(int v) {
std::cout << "按值收到 int: " << v << "\n";
}
// C++17 的 std::string_view 是只读字符串参数的更好选择(<string_view>)
// 它既能接受 std::string 也能接受 const char* 和字面量,且零拷贝
// 注意:不要同时重载 const std::string& 和 string_view,调用处会产生二义性
void inspect(std::string_view sv) {
std::cout << "字符串视图长度: " << sv.size() << " 内容: " << sv << "\n";
}
// 定义处不能再写默认参数
void log_info(const std::string& msg, int level) {
std::cout << "[INFO level=" << level << "] " << msg << "\n";
}
// 定义处重复写 port = 80 会导致编译错误
void connect(const std::string& host, int port, int timeout_ms) {
std::cout << "连接 " << host << ":" << port
<< " 超时 " << timeout_ms << "ms\n";
}
int main() {
log_info("启动完成"); // 匹配单参数版本
log_info("带级别", 3); // 匹配双参数版本
connect("example.com"); // 80 / 3000
connect("example.com", 443); // 443 / 3000
connect("example.com", 443, 10000); // 全部显式指定
std::cout << max_of(3, 5) << "\n"; // 调用 int 版本
std::cout << max_of(3.14, 2.71) << "\n"; // 调用 double 版本
// std::cout << max_of(3, 2.71); // 二义性:编译器不知道该转谁,编译错误
inspect(42); // int 版本
inspect(std::string("abc")); // std::string 可隐式转换为 string_view
inspect("字面量"); // const char* 同样可以
return 0;
}重载决议失败最常见的报错是 "call of overloaded ... is ambiguous",通常是实参需要多个"同等代价"的隐式转换。解决办法是显式转换,或者干脆换个函数名。
#内联函数
普通函数调用有跳转开销(压栈、跳地址、返回)。对一两行的小函数,这开销可能比函数体本身还大。inline 关键字建议编译器把函数体直接展开到调用处,消除调用开销。
必须澄清一个常见误解:inline 只是建议,编译器完全可以忽略;它真正的现代意义是允许在头文件中定义函数而不违反 ODR——因为内联函数在每个翻译单元都可能有副本,链接器会合并。Java 的 JIT 会自动做这件事(热点方法内联),Python/JS 的引擎也有类似优化,C++ 则把提示权交给了你(以及编译器的 -O2 优化)。
#include <iostream>
// 定义在头文件中的小函数,必须加 inline,否则多个 .cpp 包含它会导致链接期重复定义
inline int square(int x) {
return x * x;
}
// constexpr 函数天然隐含 inline 语义,且能在编译期求值,优先用它
constexpr int cube(int x) {
return x * x * x;
}
// 成员函数写在类内部时自动成为 inline 候选,无需显式写
class Counter {
public:
int value() const { return count_; } // 隐式 inline
void inc() { ++count_; }
private:
int count_{0};
};
int main() {
int n = 5;
std::cout << square(n) << "\n"; // 可能被展开为 n * n
constexpr auto c = cube(3); // 编译期就算出 27
std::cout << c << "\n";
Counter counter;
counter.inc();
counter.inc();
std::cout << counter.value() << "\n";
return 0;
}现代实践:不要为了性能手动加 inline,编译器的 -O2 判断比你准。只在"需要把小函数定义放进头文件"时才必须写它。
#函数指针与回调
函数指针是把"行为"当数据传递的 C 风格手段。在 Python 里函数是一等公民,sorted(key=len) 直接传函数对象;JS 里回调更是家常便饭;Java 8 之后用函数式接口 + Lambda。C++ 里对应的是函数指针、std::function 和 Lambda(Lambda 详见第 8 章)。
函数指针的声明语法堪称 C++ 最丑的部分之一:返回类型 (*指针名)(参数列表)。强烈建议用 using 起别名。它的局限是无法捕获上下文(不能像 Lambda 那样带着外部变量),所以现代 C++ 里回调首选 Lambda 或 std::function。
#include <functional>
#include <iostream>
#include <vector>
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
// 用 using 定义函数指针类型的别名,可读性立刻提升
// 读作:"MathFunc 是一个指向『接受两个 int、返回 int 的函数』的指针"
using MathFunc = int (*)(int, int);
// 接受函数指针作为回调,类似 Python 的 sorted(key=...) 或 JS 的回调参数
void compute_and_print(int a, int b, MathFunc op) {
std::cout << "结果 = " << op(a, b) << "\n";
}
// 函数指针数组:实现简易的"策略表",替代一长串 if/else 或 switch
int apply_all(int a, int b, const std::vector<MathFunc>& ops) {
int total = 0;
for (auto op : ops) {
total += op(a, b);
}
return total;
}
int main() {
MathFunc f = add; // 函数名会自动衰减为指针,&add 等价
std::cout << f(10, 3) << "\n"; // 13,也可以写 (*f)(10, 3)
compute_and_print(10, 3, add);
compute_and_print(10, 3, subtract);
compute_and_print(10, 3, multiply);
std::vector<MathFunc> ops{add, subtract, multiply};
std::cout << apply_all(10, 3, ops) << "\n"; // 13 + 7 + 30 = 50
// std::function 是更通用的"可调用对象包装器",能装 Lambda、函数指针、仿函数
std::function<int(int, int)> wrapped = [](int a, int b) { return a % b; };
std::cout << wrapped(10, 3) << "\n"; // 1
return 0;
}std::function 比裸函数指针更灵活(可装带捕获的 Lambda),代价是有一点类型擦除开销和可能的内存在堆分配。性能敏感的 tight loop 里用模板 + 泛型 Lambda 更合适,那是第 9 章的内容。
#小结
- 声明给签名、定义给实体;函数可声明多次但只能定义一次(ODR)。把声明放头文件、实现放
.cpp可解耦编译顺序、减少重编译。 - 参数传递四选一:小类型按值、大类型按
const T&、要修改用T&、可空用T*。Java/Python/JS 本质都是"值传递"(对象传引用副本),C++ 让你显式选择。 - 默认参数只能在参数列表尾部、且只在声明处写一次;重复写会触发重定义错误。
- 重载看的是参数列表而非返回类型;Python/JS 没有真正重载,Java 和 C++ 有。决议失败时的 "ambiguous" 错误靠显式类型转换解决。
inline主要意义是允许函数定义在头文件中不违反 ODR,性能上交给编译器的-O2即可。- 函数指针用
using别名简化书写,但无法捕获上下文;带状态的回调优先用 Lambda 或std::function。
#练习
- 写三个重载函数
area(int r)、area(int w, int h)、area(double r),分别计算圆面积、矩形面积和双精度圆面积,在main里验证重载决议选择了预期版本。 - 定义
struct Config { std::string host; int port; int timeout_ms; },写一个void dump(const Config&)打印它。再写void reset(Config&)把成员恢复默认值。体会const&和&的区别:尝试在dump里修改成员,看编译器报什么错。 - 实现一个
bool parse_int(const std::string& text, int& out):解析成功返回true并写入out。分别传入"123"、"abc"、空字符串,验证三种分支。 - 用函数指针数组实现一个四则运算计算器:从
std::vector<MathFunc>里按用户输入的索引选择运算符,处理越界索引。再改写成std::function<int(int,int)>版本,并加入一个带捕获的 Lambda(例如每次调用都把结果累加到外部变量),体会函数指针做不到的地方。