C++ 核心编程 - 函数提高

3.1 函数默认参数

在 C++ 中,函数的形参列表中的形参是可以有默认值的,语法为 返回值类型 函数名 (参数 = 默认值){}

注意1: 如果某个位置参数有默认值,那么从这个位置往后,必须都要有默认值

int func(int a, int b = 10, int c = 20){
    return a + b + c;
}

int main(){
    cout << "ret = " << func(20, 20) << endl;

    return 0;
}
ret = 60

例如,int func(int a, int b = 10, int c){} 中的 c 没有被赋默认值,就会报出如下错误:

main.cpp:5:33: error: default argument missing for parameter 3 of ‘int func(int, int, int)5 | int func(int a, int b = 10, int c){
      |                             ~~~~^
main.cpp:5:21: note: ...following parameter 2 which has a default argument
    5 | int func(int a, int b = 10, int c){
      |                 ~~~~^~~~~~

注意2: 在函数的声明/实现中,默认值只能存在于其一

int func(int a = 10, int b = 10);

int func(int a, int b){
    return a + b;
}

int main(){
    cout << "ret = " << func(20, 20) << endl;

    return 0;
}
ret = 40

3.2 函数占位参数

C++ 中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该位置,语法为 返回值类型 函数名 (数据类型){}

void func(int a, int){
    cout << "this is a func" << endl;
}

int main(){
    func(10, 10);

    return 0;
}

3.3 函数重载

3.3.1 基本语法

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

满足条件:

  • 同一个作用域下;
  • 函数名称相同;
  • 函数参数 类型不同 或者 个数不同 或者 顺序不同

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

void func(){
    cout << "==> func" << endl;
}

void func(int a){
    cout << "==> func(int)" << endl;
}

void func(double a){
    cout << "==> func(double)" << endl;
}

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

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

// int func(double a, int b){
//     cout << "==> func(double, int)" << endl;
// }

int main(){
    func(); // 1
    func(10); // 2
    func(3.14); // 3
    func(10, 3.14); // 4
    func(3.14, 10); // 5

    return 0;
}
==> func
==> func(int)
==> func(double)
==> func(int, double)
==> func(double, int)

3.3.2 注意事项

注意1: 引用作为重载条件

void func(int &a){ // int &a = num (ok)
    cout << "int &a" << endl;
}

void func(const int &a){ // const int &a = 10 (ok)
    cout << "const int &a" << endl;
}

int main(){
    int num = 10;
    func(num); // 1

    func(10); // 2

    return 0;
}

注意2: 函数重载碰到函数默认参数

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

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

int main(){
    // func(10); // 1 (ok) 2 (ok) ???

    return 0;
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_leoatliang

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

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

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

打赏作者

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

抵扣说明:

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

余额充值