【学习笔记】C++函数高级篇

目录

1.函数形参的默认参数

2.函数占位参数

3.函数的重载

4.数重载的注意事项函


 

1.函数形参的默认参数

函数在声明或者实现时可以设置默认值,但是形参的默认值不可重复定义(在声明时设置不可再实现里设置)

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

#include <iostream>
#include <string>
using namespace std;

int func(int a, int b = 10, int c = 20) //函数设置默认参数,若有传入数据,则使用传入值
//若某个位置已经有了默认参数,那么这个形参的后面的所有数据必须都要设定
//声明和实现只能有一个设定默认参数
{

    a += b + c;

    return a;
}

int main()
{

    func(10);

    cout << func(10) << endl;

    cout << func(10, 20) << endl;

    system("pause");
    return 0;
}

若某个位置已经有了默认参数,那么这个形参的后面的所有数据必须都要设定

2.函数占位参数

语法:返回值类型 函数名 (数据类型){}

int func(int,int =10)

占位参数可以有默认参数

3.函数的重载

作用:C++允许函数名相同,提高复用性

函数重载的满足条件:

函数都在同一个作用域下

函数名称相同

函数参数的类型不同,或者个数不同,或者顺序不同

函数的返回类型不能作为区分重载条件

#include <iostream>
#include <string>
using namespace std;

void func() 
{

    cout << "函数1" << endl;
}

void func(int a)
{

    cout << "函数" << a << endl;
}

int main()
{

    func(10);

    func();

    system("pause");

    return 0;
}

4.数重载的注意事项函

4.1 引用与函数重载

#include <iostream>
#include <string>
using namespace std;

void func(const int &a) 
{

    cout << "函数1常量引用" << endl;
}

void func(int &a)
{

    cout << "函数2引用" << a << endl;
}

int main()
{
    int a=10;

    func(10);//输入为常量时,编译器会选择常量引用

    func(a);//输入为变量时,选择引用函数

    system("pause");

    return 0;
}

4.2 默认参数与函数重载

有可能会出现二义性。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值