在 C++ 中,如果传递的参数数量和/或类型不同,则两个 函数 可以具有相同的名称。
这些名称相同但参数不同的函数称为重载函数。例如
// same name different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
这里,所有 4 个函数都是重载函数。
请注意,这 4 个函数的所有返回类型不一定相同。重载函数可能具有也可能不具有不同的返回类型,但它们必须具有不同的参数。例如,
// Error code
int test(int a) { }
double test(int b){ }
在这里,这两个函数具有相同的名称、相同的类型和相同数量的参数。因此,编译器将引发错误。
示例 1:使用不同参数类型进行重载
// Program to compute absolute value
// Works for both int and float
#include <iostream>
using namespace std;
// function with float type parameter
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}
// function with int type parameter
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
int main() {
// call function with int type parameter
cout << "Absolute value of -5 = " << absolute(-5) << endl;
// call function with float type parameter
cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}
输出
Absolute value of -5 = 5 Absolute value of 5.5 = 5.5

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

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