函数是C++程序的基本组成单元,是代码复用和模块化设计的核心机制。C++在继承C语言函数特性的基础上,引入了众多强大的新特性:函数重载、默认参数、内联函数、Lambda表达式、函数对象、模板函数等,使得函数设计更加灵活和强大。本文将系统全面地梳理C++函数的核心知识点,从基础语法到现代C++高级特性,帮助初学者建立完整的知识体系,也为有经验的开发者提供深入的技术参考。
一、C++函数基础
1.1 函数定义与声明
cpp
#include <iostream>
using namespace std;
// 函数声明(原型)- 告诉编译器函数的存在
int add(int a, int b);
void printMessage(const string& msg);
double calculateArea(double radius);
// 函数定义 - 具体实现
int add(int a, int b) {
return a + b;
}
void printMessage(const string& msg) {
cout << msg << endl;
}
double calculateArea(double radius) {
return 3.14159 * radius * radius;
}
int main() {
int result = add(10, 20);
printMessage("Hello, C++!");
double area = calculateArea(5.0);
cout << "结果: " << result << endl;
cout << "面积: " << area << endl;
return 0;
}
1.2 函数返回值
cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 返回基本类型
int getValue() {
return 42;
}
// 返回引用(避免拷贝)
const string& getName() {
static string name = "张三";
return name; // 返回静态变量的引用是安全的
}
// 返回指针
int* createArray(int size) {
int* arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
return arr; // 调用者负责释放内存
}
// 返回vector(移动语义,高效)
vector<int> createVector(int size) {
vector<int> vec;
for (int i = 0; i < size; i++) {
vec.push_back(i);
}
return vec; // 编译器会优化(RVO/NRVO)
}
// 返回auto(C++14)
auto multiply(int a, int b) {
return a * b; // 自动推导返回类型
}
// 返回decltype(auto)(C++14)
decltype(auto) getValueRef(int& x) {
return x; // 返回引用
}
int main() {
int val = getValue();
cout << "值: " << val << endl;
const string& name = getName();
cout << "姓名: " << name << endl;
int* arr = createArray(10);
for (int i = 0; i < 10; i++) {
cout << arr[i] << " ";
}
cout << endl;
delete[] arr; // 释放内存
vector<int> vec = createVector(5);
for (int n : vec) {
cout << n << " ";
}
cout << endl;
int x = 100;
int& ref = getValueRef(x);
cout << "引用值: " << ref << endl;
return 0;
}
二、函数重载
2.1 重载基础
cpp
#include <iostream>
using namespace std;
// 函数重载:同一作用域内,函数名相同,参数列表不同
// 1. 参数个数不同
void print() {
cout << "无参数" << endl;
}
void print(int x) {
cout << "整数: " << x << endl;
}
void print(int x, int y) {
cout << "两个整数: " << x << ", " << y << endl;
}
// 2. 参数类型不同
void display(int x) {
cout << "int: " << x << endl;
}
void display(double x) {
cout << "double: " << x << endl;
}
void display(const string& s) {
cout << "string: " << s << endl;
}
// 3. 参数顺序不同
void show(int x, double y) {
cout << "int-double: " << x << ", " << y << endl;
}
void show(double x, int y) {
cout << "double-int: " << x << ", " << y << endl;
}
// 注意:不能仅靠返回值类型区分
// int func(); // 错误:与void func()无法区分
// void func();
int main() {
print();
print(10);
print(10, 20);
display(100);
display(3.14);
display("Hello");
show(10, 3.14);
show(2.71, 20);
return 0;
}
2.2 重载与类型转换
cpp
#include <iostream>
using namespace std;
void func(int x) {
cout << "int: " << x << endl;
}
void func(double x) {
cout << "double: " << x << endl;
}
void func(char x) {
cout << "char: " << x << endl;
}
void func(const char* x) {
cout << "const char*: " << x << endl;
}
int main() {
func(10); // 精确匹配 int
func(3.14); // 精确匹配 double
func('A'); // 精确匹配 char
func("Hello"); // 精确匹配 const char*
func(10L); // long -> int 或 double? 优先 int
func(3.14f); // float -> double
func(true); // bool -> int (true->1)
return 0;
}
2.3 重载解析规则
cpp
#include <iostream>
using namespace std;
// 重载解析优先级:
// 1. 精确匹配
// 2. 类型提升(char -> int, float -> double)
// 3. 标准转换(int -> double, int -> long)
// 4. 用户定义转换
// 5. 可变参数
void test(int x) {
cout << "int: " << x << endl;
}
void test(long x) {
cout << "long: " << x << endl;
}
void test(double x) {
cout << "double: " << x << endl;
}
void test(...) {
cout << "..." << endl;
}
int main() {
test(10); // int(精确匹配)
test(10L); // long(精确匹配)
test(3.14); // double(精确匹配)
test('A'); // int(char提升为int)
test(10.0f); // double(float提升为double)
test("hello"); // ...(没有匹配,走可变参数)
return 0;
}
三、默认参数
3.1 默认参数基础
cpp
#include <iostream>
using namespace std;
// 默认参数:为函数参数提供默认值
// 规则:默认参数必须从右向左连续提供
// 正确:从右向左提供默认值
void greet(string name, string prefix = "Hello", string suffix = "!") {
cout << prefix << ", " << name << suffix << endl;
}
// 错误示例:不能跳过中间参数
// void wrong(string name = "Guest", string prefix, string suffix = "!") { }
// 多个默认参数
void printLog(string msg, int level = 0, bool timestamp = true) {
if (timestamp) {
cout << "[LOG] ";
}
if (level > 0) {
cout << "[Level " << level << "] ";
}
cout << msg << endl;
}
// 默认参数可以在声明和定义中分别指定(但不能重复)
// 通常在声明中指定默认值
void init(int x, int y = 100); // 声明中指定默认值
void init(int x, int y) { // 定义中不重复指定
cout << "x=" << x << ", y=" << y << endl;
}
int main() {
greet("张三");
greet("李四", "Hi");
greet("王五", "Welcome", "!!");
printLog("系统启动");
printLog("用户登录", 1);
printLog("错误发生", 2, true);
init(10);
init(10, 200);
return 0;
}
3.2 默认参数与函数重载
cpp
#include <iostream>
using namespace std;
// 默认参数可以替代部分重载
class Logger {
public:
// 使用默认参数(推荐)
void log(const string& msg, int level = 0, const string& tag = "INFO") {
cout << "[" << tag << "] " << string(level, ' ') << msg << endl;
}
// 等价的函数重载(代码冗余)
// void log(const string& msg) { log(msg, 0, "INFO"); }
// void log(const string& msg, int level) { log(msg, level, "INFO"); }
};
int main() {
Logger logger;
logger.log("Message");
logger.log("Warning", 2);
logger.log("Error", 0, "ERROR");
return 0;
}