C++中函数的其他用法

函数提高

函数默认参数

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

#include<iostream>
using namespace std;

int func(int a,int b=30,int c=30){
    return a+b+c;
}
// 注意事项:
// 1.如果某个位置已经有了默认参数,那么从这个位置往后,从左到右必须有默认值
// 
// int func2(int a,int b=30,int c){
//     // c必须要有默认参数,报错
//     return a+b+c;
// }

// 如果函数的声明有默认参数,函数实现就不能有默认参数。
// 声明和实现只能有一个有默认参数。
// int fun3(int a,int b=10);

// int fun3(int a,int b){
//     return a+b;
// }
//


int main(){
    cout<<func(10,20,30)<<endl;//少传输一个都不行
    // 如果传输了值,就使用传输的值,如果没有传输,就使用默认值
    
    return 0;
}

函数的占位参数

C++中函数的形参可以有占位参数,用来做占位,调用函数时必须填补该位置
语法: 返回值类型 函数名(数据类型){}
现阶段函数的占位参数存在意义不打,但是后面的课程中会用到该技术
占位参数还可以有默认参数

#include<iostream>
using namespace std;

int func(int a,int =1){
    cout<<"this is a function";
}
int main(){
    func(10,10);
    
    return 0;
}

函数重载

函数重载概述

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

函数重载满足条件:

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

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

#include<iostream>
using namespace std;

// 提高函数复用性

// 在同一个作用域下(全局作用域)
// 函数名称相同
// 函数参数类型不同,或者个数不同,或者顺序不同
void func(){
    cout<<"func"<<endl;
}
void func(int a){
    cout<<"func a"<<endl;
}
void func(double a){
    cout<<a <<endl;
}
void func(double a,int b){
    cout<<a<<b <<endl;
}
void func(int b,double a){

    cout<<b<<a <<endl;
}
// 注意:函数的返回值不可以作为函数重载的条件
// double func(double a){
//     cout<<a <<endl;
// }


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

    
    return 0;
}

函数重载的注意事项

  • 引用作为重载条件
  • 函数重载碰到函数默认参数
#include<iostream>
using namespace std;


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

//函数重载遇到默认参数
void func2(int a){
    cout<<"func2 "<<endl;
}
void func2(int a,int b=10){

    cout<<"func2 a and b"<<endl;
}

int main(){
    int a=10;
    func(a);//调用的是没有const,因为这个是变量,可读可写。
    func(10);//调用的是有const的,这个是常量,只可读
    //如果按照上面的代码,相当于 int &a=10;不合法,下面const int &a=10;合法。
    
    // func2(10); 当函数重载遇到默认参数会产生二义性
    func2(10,30);

    
    return 0;
}
posted @ 2021-05-07 00:02  Zeker62  阅读(40)  评论(0编辑  收藏  举报