原文: https://www.programiz.com/cpp-programming/function-overloading
在本教程中,我们将通过示例学习 C++ 中的函数重载。
在 C++ 中,如果传递的参数的数量和/或类型不同,则两个函数可以具有相同的名称。
这些具有相同名称但参数不同的函数称为重载函数。 例如:
// same number different argumentsint test() { }int test(int a) { }float test(double a) { }int test(int a, double b) { }
在此,所有 4 个函数均为重载函数。
请注意,所有这四个函数的返回类型都不相同。 重载的函数可以具有或可以不具有不同的返回类型,但是它们必须具有不同的参数。 例如,
// Error codeint test(int a) { }double test(int b){ }
在这里,两个函数具有相同的名称,相同的类型和相同数量的参数。 因此,编译器将引发错误。
带有不同类型参数的函数重载
// Program to compute absolute value// Works for both int and float#include <iostream>using namespace std;// function with float type parameterfloat absolute(float var){if (var < 0.0)var = -var;return var;}// function with int type parameterint absolute(int var) {if (var < 0)var = -var;return var;}int main() {// call function with int type parametercout << "Absolute value of -5 = " << absolute(-5) << endl;// call function with float type parametercout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;return 0;}
输出
Absolute value of -5 = 5Absolute value of 5.5 = 5.5

absolute()函数重载的原理
在此程序中,我们重载了absolute()函数。 根据函数调用期间传递的参数类型,将调用相应的函数。
带有不同数量的参数的函数重载
#include <iostream>using namespace std;// function with 2 parametersvoid display(int var1, double var2) {cout << "Integer number: " << var1;cout << " and double number: " << var2 << endl;}// function with double type single parametervoid display(double var) {cout << "Double number: " << var << endl;}// function with int type single parametervoid display(int var) {cout << "Integer number: " << var << endl;}int main() {int a = 5;double b = 5.5;// call function with int type parameterdisplay(a);// call function with double type parameterdisplay(b);// call function with 2 parametersdisplay(a, b);return 0;}
输出
Integer number: 5Float number: 5.5Integer number: 5 and double number: 5.5
在此,display()函数使用不同的参数调用了三次。 根据传递的参数的数量和类型,调用相应的display()函数。

display()函数重载的原理
所有这些函数的返回类型都相同,但函数重载不必如此。
注意:在 C++ 中,许多标准库函数都已重载。 例如,sqrt()函数可以将double,float,int,等作为参数。 这是可能的,因为sqrt()函数在 C++ 中已重载。
