题目:
编写一个C++程序,用来分别求2个整数、3个整数、2个双精度数和3个双精度数的最大值。要求使用重载函数来完成。
一、函数重载:
🔍 一、定义
函数重载(Function Overloading)是C++的重要特性,指在同一作用域内定义多个同名函数。这些函数通过不同的参数列表(参数类型、数量或顺序)进行区分,实现用同一函数名处理不同数据类型的操作。
⚙️ 二、核心作用
- 提高代码可读性:相同功能的函数使用统一名称
- 增强扩展性:方便添加新数据类型支持
- 简化接口:调用者无需记忆不同函数名
📌 三、具体示例
// 加法函数重载
int add(int a, int b) { // 版本1:两个int
return a + b;
}
double add(double a, double b) { // 版本2:两个double
return a + b;
}
int add(int a, int b, int c) { // 版本3:三个int
return a + b + c;
}
📊 四、优劣分析
优势 | 局限性 |
---|---|
统一接口提升可读性 | 过度使用会导致代码复杂度增加 |
扩展功能无需修改调用代码 | 参数差异必须明确 |
支持编译时多态 | 返回值类型不能作为区分依据 |
通过函数重载,我们可以用更自然的方式组织代码,例如用户之前实现的求最大值程序,正是通过重载处理了不同参数数量和类型的情况,既保持了接口的统一性,又实现了具体功能的差异性。
二、代码实现
① 2个整数:
int FindMax (int a, int b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
② 3个整数
int FindMax (int a, int b, int c)
{
int max = FindMax (a, b);
return FindMax (max, c); //借助①中代码
}
③ 两个double类型
double FindMax (double a, double b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
④ 三个double类型
double FindMax (double a, double b, double c)
{
double max = FindMax (a, b);
return FindMax (max, c); //借助③中代码
}
完整代码:
#include <iostream>
using namespace std;
int FindMax (int a, int b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
int FindMax (int a, int b, int c)
{
int max = FindMax (a, b);
return FindMax (max, c);
}
double FindMax (double a, double b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
double FindMax (double a, double b, double c)
{
double max = FindMax (a, b);
return FindMax (max, c);
}
int main ()
{
int a, b, c;
double d, e, f;
cout << "Enter three integers: ";
cin >> a >> b >> c;
cout << "The maximum of the two integers is " << FindMax (a, b) << endl;
cout << "The maximum of the three integers is " << FindMax (a, b, c) << endl;
cout << "Enter three doubles: ";
cin >> d >> e >> f;
cout << "The maximum of the two doubles is " << FindMax (d, e) << endl;
cout << "The maximum of the three doubles is " << FindMax (d,e,f)
}
输出效果: