函数重载(C++)

题目:
编写一个C++程序,用来分别求2个整数、3个整数、2个双精度数和3个双精度数的最大值。要求使用重载函数来完成。

一、函数重载:

🔍 一、定义

函数重载(Function Overloading)是C++的重要特性,指在同一作用域内定义多个同名函数。这些函数通过不同的参数列表(参数类型、数量或顺序)进行区分,实现用同一函数名处理不同数据类型的操作。

⚙️ 二、核心作用

  1. 提高代码可读性:相同功能的函数使用统一名称
  2. 增强扩展性:方便添加新数据类型支持
  3. 简化接口:调用者无需记忆不同函数名

📌 三、具体示例

// 加法函数重载
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)
}

输出效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pniubi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值