函数默认参数:

语法: 返回值类型 函数名 {数据类型 参数=默认值}{}

举例:

int func(int a=10,int b=20,int c=30)
{
     return a+b+c;
}
//以下b已经有了默认参数,那么b后面的参数也必须有默认参数。
int func(int a,int b=10,c=10)
{
     return a+b+c;
}

注意:如果在函数声明中已经有了默认参数,那么在函数定义中就不能由默认参数。即要么只有函数声明中有默认参数,要么只有函数定义中有默认参数。

函数占位参数:

语法: 返回值类型 函数名 {数据类型}{} 举例:

//注意调用该函数时,实参个数要等于形参个数,例如:func(10,10);
void func(int a,int )
{
     cout<<"This is func(int a,int)."<<endl;
}


//函数占位参数也是可以有默认参数的
//由于占位参数有默认参数,所以只需要传一个参数就可以调用func
//例如:func(10);
void func(int a,int =10)
{
     cout<<"This is func(int a,int=10)."<<endl;
}

函数重载:函数名可以相同,提高复用性

函数重载的条件:

(1)同一个作用域下

(2)函数名称相同

(3)函数参数类型不同 或者 个数不同 或者 顺序不同

注意:函数返回值类型不同不可以作为函数重载的条件

例子如下:

void func(int a)
{
    count<<"This is void func(int a)."<<endl;
}

// 参数类型不同
void func(double a)
{
    count<<"This is void func(double a)."<<endl;
}

//参数个数不同
void func(double a,int b)
{
    count<<"This is void func(double a,int b)."<<endl;
}

//参数顺序不同
void func(int a,double b)
{
    count<<"This is void func(int a,double b)."<<endl;
}

函数重载的注意事项:

//引用作为重载条件,无法通过func(常数)调用
void func(int &a)
{
    cout<<"This is func(int &a)."<<endl;
}

// const配合引用重载,可通过func(常数)调用
void func(const int &a)
{
    cout<<"This is func(const int &a)."<<endl;
}
//函数重载碰到默认参数,容易出现二义性
void func(int a,int b=10)
{
    cout<<"This is func(int a)."<<endl;
}

void func(int a)
{
    cout<<"This is func(int a)."<<endl;
}
//以上调用func(10);函数重载碰到默认参数,就可能会出现二义性
//应该尽量避免这种情况出现

总结一下:函数重载,只要参数部分不完全一致(变量名不一致不算),那么就是函数重载,因为通过函数的参数部分可以区分开这些函数。