是的,c++++ 允许函数重载和函数默认参数。函数重载可创建具有相同名称但不同参数列表的函数,编译器根据参数类型决定调用哪个重载。函数默认参数可为部分参数提供默认值,在没有提供参数时使用默认值。

C++ 函数重载和函数默认参数
函数重载
函数重载允许我们在同一个类中定义具有相同名称但参数列表不同的多个函数。编译器将根据调用时提供的参数类型来决定调用哪个重载函数。
立即学习“C++免费学习笔记(深入)”;
语法:
return_type function_name(parameter_list_1); return_type function_name(parameter_list_2); ...
函数默认参数
函数默认参数允许我们在声明函数时为某些参数提供默认值。如果在调用时未提供这些参数,则使用默认值。
语法:
return_type function_name(parameter_type parameter_name = default_value);
实战案例
假设我们有一个函数 calculateArea,该函数可以计算圆形或矩形的面积。我们可以使用函数重载来实现:
#include <iostream>
using namespace std;
// 计算圆形的面积
double calculateArea(double radius) {
return 3.14159 * radius * radius;
}
// 计算矩形的面积
double calculateArea(double length, double width) {
return length * width;
}
int main() {
double radius, length, width;
// 计算圆形的面积
cout << "Enter the radius: ";
cin >> radius;
cout << "The area of the circle is: " << calculateArea(radius) << endl;
// 计算矩形的面积
cout << "Enter the length and width of the rectangle: ";
cin >> length >> width;
cout << "The area of the rectangle is: " << calculateArea(length, width) << endl;
return 0;
}在该案例中,calculateArea 函数具有两个重载:
calculateArea(double radius) 用于计算圆形的面积,并使用函数默认参数为 radius 指定默认值 0。calculateArea(double length, double width) 用于计算矩形的面积,没有使用函数默认参数。以上就是C++ 函数重载和函数默认参数的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号