函数
C++ / 函数
28%
基本函数
函数重载
递归函数
练习例题
函数定义与声明
// 函数声明(原型)
int add(int a, int b);
void printMessage(string msg = "Hello"); // 带默认参数
double calculateArea(double radius);
// 函数定义
int add(int a, int b) {
return a + b;
}
void printMessage(string msg) {
cout << msg << endl;
}
double calculateArea(double radius) {
const double PI = 3.14159;
return PI * radius * radius;
}
// 内联函数
inline int max(int a, int b) {
return (a > b) ? a : b;
}
// 带有多个返回值的函数(使用引用参数)
void getMinMax(const vector<int>& numbers, int& min, int& max) {
if (numbers.empty()) return;
min = max = numbers[0];
for (int num : numbers) {
if (num < min) min = num;
if (num > max) max = num;
}
}
- 函数声明告诉编译器函数的接口
- 函数定义包含了函数的具体实现
- 内联函数可以提高性能,但只适用于简单函数
- 可以使用引用参数来返回多个值