C++高级函数

默认参数

提要:其实就是参数后面多跟了具体的数
注意:如果中途有一个变量有默认参数的话,后边所有的变量都要跟默认值

#include<iostream>
using namespace std;
// int f(int a,int b,int c)
// {
//     return a+b+c;
// }
int f(int a,int b = 10,int c = 20)
//形参默认值会被下列实参改变
//注意,写了默认值后,后边每一个都要写默认参数
{
    return a + b + c;
}
int main()
{
    cout<<f(10);

    return 0;
}



占位参数

提要:参数后边多跟了一个数据类型

#include <iostream>
using namespace std;
void f(int s, int)
{
    cout << "this is my code." << "\n";
}
int main()
{
    f(10, 10);
    return 0;
}



函数重载

提要:就是一个相同函数可以出现多次
条件:
1.在同一作用域下
2.函数名相同
3.函数参数类型不同 || 个数不同 || 参数顺序不同

// #include<iostream>
// using namespace std;
// void f()
// {
//     cout<<"22222"<<"\n";
// }

// void f(int a)
// {
//     cout<<"11111"<<"\n";
// }
// int main()
// {
//     f(10);
//     return 0;
// }


#include<iostream>
using namespace std;
//引用作为重载的条件
void f(int &a)
{
    cout<<"111111"<<"\n";
}
void f(const int &a)
{
    cout<<"22222"<<"\n";
}




//函数重载遇到默认参数
void f2(int a)
{
    cout<<"33333333"<<"\n";
}
void f2(int a,int b = 10)
{
    cout<<"44444444"<<"\n";
}

int main()
{
    int a = 10;
    f(a);//走(int &a)那个部分
    f(10);//走(const int &a)那个部分
    //f2(10);//出现歧义,f2两个都可以调用
    return 0;
}
posted @ 2025-02-05 13:01  Alaso_shuang  阅读(40)  评论(0)    收藏  举报
2 3
4