研一寒假C++复习笔记--函数使用的注意事项

目录

1--默认参数的使用

2--函数占位参数

3--函数重载


1--默认参数的使用

① 函数某个参数有默认值,则此参数往后的参数都应设置默认值;

int test1(int a = 1, int b, int c); // ×

int test1(int a, int b = 1, int c = 2); // √

② 函数声明和函数实现不能同时设置参数默认值;

// 错误用法:定义和实现都设置参数值
int test2(int a = 1, int b = 2);

int test2(int a = 1, int b = 2){
    return a + b;
}

// 正确用法:
int test2(int a = 1, int b = 2);

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

// 正确用法:
int test2(int a, int b);

int test2(int a = 1, int b = 2){
    return a + b;
}

2--函数占位参数

① 占位参数可以用默认值

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

        int = 20 就是为占位参数设置默认值,占位参数用数据类型来指定,不需要使用具体的变量名;

3--函数重载

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

② 重载条件:在同一个作用域下,函数名称相同,函数参数类型、参数个数或参数顺序不同;函数的返回值不可以作为函数重载的条件;

#include <iostream>

void func(){
    std::cout << "func() calling .." << std::endl;
}

void func(int a){
    std::cout << "func(int a) calling .." << std::endl;
}

void func(double a){
    std::cout << "func(double a) calling .." << std::endl;
}

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

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

int main(){

    func();

    int a = 10;
    func(a);

    double b = 10;
    func(b);

    func(a, b);
    func(b, a);
    return 0;
}

③ 引用作为重载

#include <iostream>

void func(int &a){
    std::cout << "func(int &a) calling .." << std::endl;
}

void func(const int &a){
    std::cout << "func(const int &a) calling .." << std::endl;
}
// int 和 const int类型不同,满足重载的条件

int main(){
    func(10);
    // int &a = 10 不合法
    // const int &a = 10 合法
    // 因此调用的是func(const int &a)
    return 0;
}

④ 函数重载与默认参数的冲突

#include <iostream>

void func(int a){
    std::cout << "func(int a) calling .." << std::endl;
}

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

int main(){
    func(10);

    return 0;
}

         上面的代码是错误的,出现二义性,因为 func(10) 可以调用两个函数;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值