Appearance
L4_04 函数
一、函数的定义、调用、声明
1.1 函数定义
cpp
#include <iostream>
using namespace std;
// 返回值类型 函数名(参数列表) { 函数体 }
int add(int a, int b) {
return a + b;
}1.2 函数调用
cpp
int main() {
int result = add(3, 5); // 调用函数
cout << "结果: " << result << endl; // 输出8
return 0;
}1.3 函数声明
cpp
// 函数声明(原型)
int add(int a, int b);
int main() {
cout << add(3, 5) << endl; // 可以调用
return 0;
}
// 函数定义
int add(int a, int b) {
return a + b;
}二、形参、实参
2.1 形参
函数定义时声明的参数,用于接收调用时传入的值。
2.2 实参
函数调用时传递给函数的实际值。
2.3 示例
cpp
void printInfo(string name, int age) { // name和age是形参
cout << name << "今年" << age << "岁" << endl;
}
int main() {
printInfo("Alice", 18); // "Alice"和18是实参
return 0;
}三、全局作用域、局部作用域
3.1 局部变量
cpp
void func() {
int x = 10; // 局部变量,只在func函数内有效
cout << x << endl;
}
int main() {
// cout << x << endl; // 错误,x未定义
return 0;
}3.2 全局变量
cpp
int global_var = 100; // 全局变量,整个程序都可以访问
void func() {
cout << global_var << endl; // 可以访问
}
int main() {
cout << global_var << endl; // 可以访问
return 0;
}3.3 同名变量的优先级
cpp
int x = 100; // 全局变量
void func() {
int x = 10; // 局部变量,覆盖全局变量
cout << x << endl; // 输出10
}四、值传递、引用传递
4.1 值传递
cpp
void increment(int num) {
num++; // 修改的是副本
}
int main() {
int x = 5;
increment(x);
cout << x << endl; // 输出5,原值不变
return 0;
}4.2 引用传递
cpp
void increment(int &num) {
num++; // 修改的是原值
}
int main() {
int x = 5;
increment(x);
cout << x << endl; // 输出6,原值被修改
return 0;
}4.3 const 引用
cpp
void printValue(const int &num) {
// num++; // 错误,不能修改const引用
cout << num << endl;
}五、函数重载
5.1 概念
多个函数可以有相同的名字,但参数列表不同。
5.2 示例
cpp
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
cout << add(1, 2) << endl; // 调用int版本
cout << add(1.5, 2.5) << endl; // 调用double版本
cout << add(1, 2, 3) << endl; // 调用三参数版本
return 0;
}六、递归函数
6.1 概念
函数调用自身。
6.2 示例:计算阶乘
cpp
int factorial(int n) {
if (n == 0) return 1; // 基准条件
return n * factorial(n - 1); // 递归调用
}
int main() {
cout << factorial(5) << endl; // 输出120
return 0;
}七、示例程序
cpp
#include <iostream>
using namespace std;
// 函数声明
int max(int a, int b);
void swap(int &a, int &b);
int main() {
int x = 10, y = 20;
cout << "最大值: " << max(x, y) << endl;
cout << "交换前: x=" << x << ", y=" << y << endl;
swap(x, y);
cout << "交换后: x=" << x << ", y=" << y << endl;
return 0;
}
// 求最大值
int max(int a, int b) {
return (a > b) ? a : b;
}
// 交换两个数(引用传递)
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}