C++函数的定义、参数传递、重载、嵌套
一. 函数的定义
1. 基本语法
在C++中,函数由函数头和函数体组成。函数头包含函数的返回类型、函数名和参数列表(可以为空),函数体包含在一对花括号内,是实现函数功能的代码块。
例如,定义一个简单的函数来计算两个整数的和:
int add(int num1, int num2) { return num1 + num2; }
这里int是函数的返回类型,表示函数将返回一个整数。add是函数名,(int num1, int num2)是参数列表,其中num1和num2是函数的参数,在函数体中可以使用这些参数进行计算。
2. 函数的返回值
函数可以返回一个值(除了void类型的函数)。返回值的类型在函数头中指定。例如,上述add函数返回两个整数相加的结果。如果函数不需要返回值,则使用void作为返回类型。
void printMessage() { std::cout << "Hello, World!" << std::endl; }
二. 函数的参数传递
1. 值传递
在值传递中,函数接收的是实参的值的副本。对函数内部参数的修改不会影响到外部的实参。
void increment(int num) { num++; std::cout << "Inside the function, num = " << num << std::endl; } int main() { int num = 5; increment(num); std::cout << "Outside the function, num = " << num << std::endl; return 0; }
输出结果为:
Inside the function, num = 6 Outside the function, num = 5
2. 引用传递
引用传递允许函数直接操作实参变量。在函数定义时,参数类型后面加上&表示引用类型。
void incrementByReference(int& num) { num++; std::cout << "Inside the function, num = " << num << std::endl; } int main() { int num = 5; incrementByReference(num); std::cout << "Outside the function, num = " << num << std::endl; return 0; }
输出结果为:
Inside the function, num = 6 Outside the function, num = 6
3. 常量引用传递
当函数不需要修改传入的参数,但参数可能是较大的数据类型(如结构体、类对象)时,为了避免不必要的复制,可以使用常量引用传递。
void printArray(const int& arr[], int size) { for (int i = 0; i < size; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; }
三. 函数的重载
函数重载是指在同一个作用域内,可以定义多个同名函数,只要它们的参数列表不同(参数个数、类型或者顺序不同)。
int add(int num1, int num2) { return num1 + num2; } double add(double num1, double num2) { return num1 + num2; } int add(int num1, int num2, int num3) { return num1 + num2 + num3; }
这样,根据实参的类型和个数,编译器会自动调用合适的add函数。
int main() { int result1 = add(3, 5); double result2 = add(3.5, 2.5); int result3 = add(1, 2, 3); return 0; }
四. 函数的嵌套
在C++中,函数内部可以定义其他函数,这种函数称为嵌套函数。不过,嵌套函数的作用域仅限于包含它的函数内部。
void outerFunction() { std::cout << "This is the outer function." << std::endl; void innerFunction() { std::cout << "This is the inner function." << std::endl; } innerFunction(); }
需要注意的是,在C++标准中,在函数内部定义函数不是所有编译器都支持的特性,在一些现代的C++编程风格中也不常用。更多的是使用类的成员函数等方式来组织代码结构。