【C++】函数重载

函数重载

C++支持在同⼀作⽤域中出现同名函数,但是要求这些同名函数的形参不同,可以是参数个数不同或者类型不同。这样C++函数调用就表现出了多态行为,使⽤更灵活。C语言是不支持同⼀作用域中出现同名函数的。

1.参数类型不同

#include <iostream>
using namespace std;

// 1、参数类型不同
int test1(int a, int b)
{
    cout<< "参数类型不同1" <<endl;
    return a + b;
}

double test1(double a, double b)
{
    cout<< "参数类型不同2" <<endl;
    return a + b;
}

int main()
{
    test1(1, 2);
    test1(1.1, 2.2);

    return 0;
}

2.参数个数不同

#include <iostream>
using namespace std;

// 2、参数个数不同
void test2()
{
    cout<< "参数个数不同1" <<endl;
}

void test2(int a)
{
    cout<< "参数个数不同2" <<endl;
}

int main()
{
    test2();
    test2(10);

    return 0;
}

3.参数类型顺序不同

#include <iostream>
using namespace std;

// 3、参数类型顺序不同
void test3(int a, char b)
{
    cout<< "参数类型顺序不同1" <<endl;
}

void test3(char b, int a)
{
    cout << "参数类型顺序不同2" << endl;
}


int  main()
{
    test3(1, 'a');
    test3('a', 1);

    return 0;
}

4.返回值不同不能作为重载条件

因为调用时也无法区分
在这里插入图片描述

5.存在歧义会报错

#include <iostream>
using namespace std;

// 下⾯两个函数构成重载
// test5()调⽤时,会报错,存在歧义,编译器不知道调⽤谁
void test5()
{
    cout<< "test5()" <<endl;
} 

void test5(int a = 10)
{
    cout<< "test5(int a)" <<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值