函数拓展
美丽新科技BLOG

函数拓展

刘纪彤
2年前发布

函数拓展

函数默认参数

在C++中函数是可以拥有默认参数的。例如以下:

int func(int a=10,int b=20)
{
    return a+b;
}

值得注意的是,如果某个位置已经有了默认值,那么从这个位置往后,都要有默认值。如果函数声明了默认值,那么函数实现的时候就不能有默认参数了

//函数拓展-1
#include<iostream>
using namespace std;
int fuction(int a,int b=19)
{
    return a+b;
}
int fuction2(int b=1,int c=1)
{
    return b+c;
}
int main()
{
    int c=fuction(20);
    cout<<c<<endl;
    c=fuction2();
    cout<<c<<endl;
    c=fuction(1,2);
    cout<<c<<endl;
}

输出结果:

39
2
3

通俗易懂

占位参数

以下例子就是一个占位参数的例子:

int fuction(int a,int);

值得注意的是,调用的时候必须填补这个占用参数,现阶段意义不大,暂略。

函数重载

在C++中函数可以发生重载。其函数名称是相同的。想要重载,必须保证函数们在同一个作用域下,同时用相同的函数名称,传递的参数必须不同,包括但不限于,参数类型不同,个数不同,顺序不同,看例子:

//函数拓展-2
#include<iostream>
using namespace std;
//函数重载需要函数都在同一个作用域下
void func()
{
    
    cout << "func 的调用!" << endl;
}
void func(int a)
{
    a++;
    cout << "func (int a) 的调用!" << endl;
}
void func(double a)
{
    a++;
    cout << "func (double a)的调用!" << endl;
}
void func(int a ,double b)
{
    a++;
    b++;
    cout << "func (int a ,double b) 的调用!" << endl;
}
void func(double a ,int b)
{
    a++;
    b++;
    cout << "func (double a ,int b)的调用!" << endl;
}

//函数返回值不可以作为函数重载条件
//int func(double a, int b)
//{
//    cout << "func (double a ,int b)的调用!" << endl;
//}


int main() {

    func();
    func(10);
    func(3.14);
    func(10,3.14);
    func(3.14 , 10);
    return 0;
}

运行结果

func 的调用!
func (int a) 的调用!
func (double a)的调用!
func (int a ,double b) 的调用!
func (double a ,int b)的调用!

一目了然

特殊地:

  • 引用作为重载条件
  • 函数重载碰到函数默认参数
//函数拓展-3
#include<iostream>
using namespace std;
//函数重载注意事项
//1、引用作为重载条件

void func(int &a)
{
    a++;
    cout << "func (int &a) 调用 " << endl;
}
void func(const int &a)
{
    cout<<a<<endl;
    cout << "func (const int &a) 调用 " << endl;
}
//2、函数重载碰到函数默认参数
void func2(int a, int b = 10)
{
    a++;
    b++;
    cout << "func2(int a, int b = 10) 调用" << endl;
}
void func2(int a)
{
    a++;
    cout << "func2(int a) 调用" << endl;
}
int main() {
    
    int a = 10;
    func(a); //调用无const
    func(10);//调用有const
    func2(10,10);
    //func2(10); //碰到默认参数产生歧义,需要避免
    return 0;
}

输出结果:

func (int &a) 调用
10
func (const int &a) 调用
func2(int a, int b = 10) 调用

通俗易懂

喜欢就支持一下吧
点赞 0 分享 收藏
评论 抢沙发
OωO
取消