在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;
}
在這個示例中,我們為加法、減法、乘法和除法運算符提供了重載函數。每個函數都有兩個版本,一個用于整數參數,另一個用于浮點數參數。這樣,我們可以根據需要選擇合適的函數版本來執行相應的操作。