首页  >  文章  >  后端开发  >  C++ 函数重载和函数默认参数

C++ 函数重载和函数默认参数

王林
王林原创
2024-04-13 18:03:02663浏览

是的,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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn