C++ 函数

1. 函数的默认参数

// 默认参数
// 1. 如果某个位置已经有了默认参数,那么从这个位置往后,从左到右都必须有默认值
int test20(int a, int b, int c = 1, int d = 1)
{
    return a + b + c + d;
}

// 2.声明和实现,只能有一个有默认参数
//   如果函数的声明有默认参数,那么函数的实现就不能有默认参数
//   如果函数函数的实现有默认参数,那么函数的声明就不能有默认参数

int test21(int a, int b, int c = 0);

int test21(int a, int b , int c)
{
    return a + b + c;
}

int test22(int a, int b, int c);

int test22(int a, int b , int c = 1)
{
    return a + b + c;
}

2. 函数的占位参数

// 占位参数
void test23(int a, int)
{
    cout << "test23" << endl;
}

int main(int argc, const char * argv[]) {
    test23(10, 1); // 调用必须传2个参数
    return 0;
}

3. 函数的重载

// 函数的重载
// 作用:函数名可以相同,提高复用性
// 函数重载满足条件
/**
 1. 同一个作用域下
 2. 函数名称相同
 3. 函数参数类型不同 或者 个数不同  或者顺序不同
 注意: 函数的返回值不可以作为函数重载的条件
 */

void test24(int a, double b)
{
    cout << "test24--1" << endl;
}

void test24(int a, double b, double c)
{
    cout << "test24--2" << endl;
}

void test24(double b ,int a)
{
    cout << "test24--3" << endl;
}

/* 返回值类型不同,不能作为函数重载条件
int test24(double b ,int a)
{
    cout << "test24--3" << endl;
}*/

4. 函数重载注意事项

// 函数重载注意事项
// 1. 引用作为重载条件

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

void test25(const int &a)
{
    cout << "const -- test25" << endl;
}

// 2. 函数重载碰到默认参数
void test26(int a, int b = 1)
{
    cout << "test26" << endl;
}

void test26(int a)
{
    cout << "test26" << endl;
}
int main(int argc, const char * argv[]) {
    
    int a = 1;
    int &r_a = a;
    const int &c_r_a = a;
    
    r_a = 2;
    
    // Tips:
    cout << "a = " << a << endl; // 2
    cout << "r_a = " << r_a << endl; // 2
    cout << "c_r_a = " << c_r_a << endl; // 2
    
    test25(a); // test25
    /**
     为什么 test25(10) 调用的是 :void test25(const int &a)
     因为:如果调用void test25(int &a),那么int &a = 10; 不合法
     所以:调用void test25(const int &a),const int &a = 10; 是合法的,会转为 int temp = 10; const int &a = temp;
     */
    test25(10); // const -- test25
    test25(r_a); // test25
    test25(c_r_a);// const -- test25
    
//    test26(1); // 函数带有默认参数,调用两个都合法,会导致的二义性, 所以碰到默认参数,有时候是不能函数重载的
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值