c++函数特性

文章介绍了C++中函数默认参数的使用规则,如参数从有默认值的位置开始都需有默认值,声明和实现不能同时有默认参数。同时,文章阐述了函数重载的概念,允许在同一作用域内函数名相同但参数列表不同,提高了代码的复用性。并提醒了函数重载时的注意事项,包括引用作为重载条件和避免默认参数导致的二义性问题。
摘要由CSDN通过智能技术生成

函数

函数默认参数

在C++中,函数的形参列表中的形参是可以有默认值的。

语法:返回值类型 函数名 (参数 =默认值){}

int Func_funcAdd(int a, int b = 200, int c = 300)
{
    return a + b + c;
}
//如果函数声明有默认值,函数实现的时候就不能有默认参数
//声明和实现只能有一个默认参数
int Func_funcAdd02(int a = 123, int b = 345);
int Func_funcAdd02(int a, int b)
{
    return a + b;
}

void Func_basic()
{
    cout << Func_funcAdd(100) << endl; //600,如果未传入数据,使用默认值
    cout << Func_funcAdd(100,400) << endl;  //800,如果传入数据,则使用传入数据

    cout << Func_funcAdd02(100, 400) << endl; //500
    cout << Func_funcAdd02() << endl;  //468
}

注意:

1. 如果某个位置参数有默认值,那么从这个位置往后,从左向右,必须都要有默认值

在这里插入图片描述

2. 如果函数声明有默认值,函数实现的时候就不能有默认参数

在这里插入图片描述

函数占位参数

1、占位参数必须填补
在这里插入图片描述

函数重载

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

函数重载条件
1、函数重载都需要在同一个作用域下
2、函数名字相同
3、函数参数类型不同/参数个数不同/参数顺序不同
4、返回值不同的函数不是函数重载

void Func_funcReloadTest()
{
    cout << "func 的调用!" << endl;
}
void Func_funcReloadTest(int a)
{
    cout << "func (int a) 的调用!" << endl;
}
void Func_funcReloadTest(double a)
{
    cout << "func (double a)的调用!" << endl;
}
void Func_funcReloadTest(int a, double b)
{
    cout << "func (int a ,double b) 的调用!" << endl;
}
void Func_funcReloadTest(double a, int b)
{
    cout << "func (double a ,int b)的调用!" << endl;
}
//函数返回值不可以作为函数重载条件
//int func(double a, int b)
//{
// cout << "func (double a ,int b)的调用!" << endl;
//}

void Func_funcReload()
{
    Func_funcReloadTest(); 
    Func_funcReloadTest(10);
    Func_funcReloadTest(3.14);
    Func_funcReloadTest(10, 3.14);
    Func_funcReloadTest(3.14, 10);
}

在这里插入图片描述

函数重载注意事项
1、引用作为重载条件
2、函数重载碰到函数默认参数
*/

//引用作为重载条件
void Func_funcReloadTest_Attention01(int &a)
{
    cout << "func (int &a) 调用 " << endl;
}
void Func_funcReloadTest_Attention01(const int &a)
{
    cout << "func (const int &a) 调用 " << endl;
}
//函数重载碰到函数默认参数 ,会出现二义性,避免
void Func_funcReloadTest_Attention02(int a, int b = 10)
{
    cout << "func (int a, int b = 10) 调用 " << endl;
}
void Func_funcReloadTest_Attention02(int a)
{
    cout << "func (int a) 调用 " << endl;
}

void Func_funcReload()
{
    int a = 34;
    Func_funcReloadTest_Attention01(a); //调用的是 非const 的函数
    Func_funcReloadTest_Attention01(34); //调用的是 加const 的函数

    //Func_funcReloadTest_Attention02(10);//err,函数重载碰到默认参数会出现二义性,尽量避免
    Func_funcReloadTest_Attention02(67,57);//OK
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值