在C++中,函数重载(Overloading)是指在同一个作用域内声明多个同名函数,但它们的参数列表不同
#include <iostream>
using namespace std;
// 函数重载:加法运算符
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
// 函数重载:减法运算符
int subtract(int a, int b) {
return a - b;
}
double subtract(double a, double b) {
return a - b;
}
// 函数重载:乘法运算符
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
// 函数重载:除法运算符
int divide(int a, int b) {
if (b == 0) {
cout << "Error: Division by zero" << endl;
return INT_MAX;
}
return a / b;
}
double divide(double a, double b) {
if (b == 0) {
cout << "Error: Division by zero" << endl;
return NAN;
}
return a / b;
}
int main() {
int a = 10, b = 5;
double c = 10.5, d = 5.5;
cout << "Add: " << add(a, b) << endl;
cout << "Add: " << add(c, d) << endl;
cout << "Subtract: " << subtract(a, b) << endl;
cout << "Subtract: " << subtract(c, d) << endl;
cout << "Multiply: " << multiply(a, b) << endl;
cout << "Multiply: " << multiply(c, d) << endl;
cout << "Divide: " << divide(a, b) << endl;
cout << "Divide: " << divide(c, d) << endl;
return 0;
}
在这个示例中,我们为加法、减法、乘法和除法运算符提供了重载函数。每个函数都有两个版本,一个用于整数参数,另一个用于浮点数参数。这样,我们可以根据需要选择合适的函数版本来执行相应的操作。