导航菜单

C++编程/函数
课程进度 29% · 第6/18章6/18章 · 标签 1/4
1

函数定义与声明

cpp
1
// 函数声明(原型)
2
int add(int a, int b);
3
void printMessage(string msg = "Hello");
4
double calculateArea(double radius);
5
 
6
// 函数定义
7
int add(int a, int b) {
8
return a + b;
9
}
10
 
11
void printMessage(string msg) {
12
cout << msg << endl;
13
}
14
 
15
double calculateArea(double radius) {
16
const double PI = 3.14159;
17
return PI * radius * radius;
18
}

📖函数声明告诉编译器函数的接口,函数定义包含具体实现。声明可以多次,定义只能一次

2

内联函数与引用参数

cpp
1
// 内联函数
2
inline int max(int a, int b) {
3
return (a > b) ? a : b;
4
}
5
 
6
// 多个返回值(使用引用参数)
7
void getMinMax(const vector<int>& numbers,
8
int& min, int& max) {
9
if (numbers.empty()) return;
10
min = max = numbers[0];
11
for (int num : numbers) {
12
if (num < min) min = num;
13
if (num > max) max = num;
14
}
15
}

📖内联函数可提高性能但只适用于简单函数。引用参数可以「返回」多个值

函数使用要点:

  • 声明在前,定义在后,或定义直接代替声明
  • 默认参数从右向左提供
  • 内联函数适用于频繁调用的小函数
  • 引用参数避免拷贝,适合返回多个值