C++ 函数重载

本文深入探讨了C++函数重载的概念、实现方法及应用案例,包括参数列表的不同、函数调用时的选择过程以及与函数指针的交互。通过实例展示了如何在不同场景下灵活运用函数重载来优化代码结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++函数重载

 同一作用域中 函数名相同 参数列表不同的函数构成重载关系。

 参数列表不同 : 类型不同 、个数不同、参数顺序不同

 调用函数时会根据传入的参数值的类型选择对函数。
#include <iostream>
using namespace std;

int getmax(int x,int y)
{
    cout << "getmax(int,int)" << endl;
    return  x>y?x:y;
}

int getmax(int x,double y)
{
      cout << "getmax(int,double)" << endl;
    return  x>y?x:y;
}
int main()
{
    getmax(1,2);
    getmax(1,2.5);
}

函数重载 在使用函数指针调用函数时会根据指针的类型选择对合适的函数。

#include <iostream>

using namespace std;

int getmax(int x,int y)
{
    cout << "getmax(int,int)" << endl;
    return  x>y?x:y;
}
double getmax(double x,int y)
{
    cout << "getmax(double,int)" << endl;
    return  x>y?x:y;
}
double getmax(int x,double y)
{
    cout << "getmax(int,double)" << endl;
    return  x>y?x:y;
}
double (*pgetmax)(double x,int y);

double (*pfun)(int x,double y);

int main()
{
    getmax(1,2);
    getmax(1,2.5);
    getmax(2.5,3);

    pgetmax = getmax;
    pgetmax(1.5,100);
    pfun = getmax;
    pfun(100,2.5);
}

函数重载的原理

 c++ 语言中生成调用函数名时 不但要考虑函数名 还要考虑参数列表。

 c  语言中生成调用函数名时 只考虑函数名。

c++函数重载引入的问题

 跨编译器调用问题

解决方式

extern "C" int getmax(int x,int y);

按照c语言的方式 来产生调用的函数名

callcfun.c

#include <stdio.h>
int getmax(int x,int y)
{
    printf("c fun getmax(int,int)\n");
    return x>y?x:y;
}

cfun.cpp

#include <iostream>
using namespace std;
extern "C" int  getmax(int x,int y);
int main()
{
    cout << getmax(1,100) << endl;
}
### C++函数重载的概念 在 C++ 编程语言中,允许多个函数具有相同的名称,前提是这些函数参数列表有所不同。这种特性被称为函数重载 (Function Overloading)[^2]。 通过函数重载,同一个函数名可以根据不同的输入参数执行不同的操作,从而提高代码可读性灵活性。需要注意的是,返回值类型的差异不足以构成有效的函数重载条件;只有当形参的数量、类型或顺序存在区别才能形成合法的重载版本[^1]。 ### 实现方式与注意事项 为了实现函数重载,在定义同名的不同函数需确保各函数之间至少有一个形式参数上的差别: - 参数数量不同; - 参数数据类型各异; - 参数次序有所变化。 如果两个函数仅因返回类型相异,则不会被视作有效重载,并可能导致编译错误[^3]。 ### 示例代码展示 下面给出几个简单的例子来说明如何正确运用这一机制: ```cpp #include <iostream> using namespace std; // 不同参数数目 void display() { cout << "无参数" << endl; } void display(int num) { cout << "整数:" << num << endl; } // 不同参数类型 double add(double a, double b){ return a+b; } int add(int a,int b){ return a+b; } // 同一作用域内不允许仅有返回值类型不同 /* 错误示范 */ /* float divide(float dividend,float divisor); int divide(int dividend,int divisor); // 这里会引发冲突 */ int main(){ int i=5,j=7,k; float f1=2.0,f2=3.0,g; k=add(i,j); g=add(f1,f2); cout<<"Integer Sum:"<<k<<endl; cout<<"Float Sum:"<<g<<endl; return 0; } ``` 上述实例展示了基于参数数量以及参数类型的两种常见情况下的函数重载应用案例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值