C++函数重载

文章详细介绍了C++中的函数重载机制,包括重载条件(同一作用域、同名、参数不同),并强调返回值类型不能作为重载依据。同时,提到了引用作为重载条件以及函数默认参数在重载中可能导致的问题,提供了示例代码进行说明。
摘要由CSDN通过智能技术生成

函数名可以相同,提高复用性。

函数重载的条件:

1. 同一个作用域下

2. 函数名称相同

3. 函数参数 类型不同 或者 个数不同 或者 顺序不同

注意:函数的返回值不可以作为函数重载的条件

#include <iostream>
using namespace std;

void func()
{
    cout << "Call func. " << endl;
}

void func(int a)
{
    cout << "Call func(int a). " << endl;
}

void func(double a)
{
    cout << "Call func(double a). " << endl;
}

void func(int a, double b)
{
    cout << "Call func(int a, double b). " << endl;
}

// Same funcation cannot survive together
// void func(){
//     cout<<"Call func! "<<endl;
// }

// 无法重载仅按返回类型区分的函数
// int func(int a, double b)
// {
//     cout << "Call func(int a, double b). " << endl;
// }

int main()
{
    func();
    func(10);
    func(0.01);
    func(1, 0.5);

    return 0;
}

函数重载的注意事项:

引用作为重载条件

函数重载碰到函数默认参数

#include <iostream>
using namespace std;

// 当func(int &a)和func(const int &a)同时存在时,会优先调func(int &a)
void func(int &a)
{
    cout << "Call func(int &a). " << endl;
}

void func(const int &a)
{
    cout << "Call func(const int &a). " << endl;
}

void func2(int a, int b = 10)
{
    cout << "Call func2(int a, int b). " << endl;
}

void func2(int a)
{
    cout << "Call func2(int a). " << endl;
}

int main()
{
    int a = 10;
    func(a);
    // 如果想调用func(const int &a)
    func(10);
    // or
    const int b = 10;
    func(b);

    // func2(1);  此时会出错,当函数重载碰到默认参数,出现二义性,报错,尽量避免出现这种情况
    func2(1, 2);

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值