函数
函数默认参数
在C++中,函数的形参列表中的形参是可以有默认值的。
语法:返回值类型 函数名 (参数 =默认值){}
int Func_funcAdd(int a, int b = 200, int c = 300)
{
return a + b + c;
}
//如果函数声明有默认值,函数实现的时候就不能有默认参数
//声明和实现只能有一个默认参数
int Func_funcAdd02(int a = 123, int b = 345);
int Func_funcAdd02(int a, int b)
{
return a + b;
}
void Func_basic()
{
cout << Func_funcAdd(100) << endl; //600,如果未传入数据,使用默认值
cout << Func_funcAdd(100,400) << endl; //800,如果传入数据,则使用传入数据
cout << Func_funcAdd02(100, 400) << endl; //500
cout << Func_funcAdd02() << endl; //468
}
注意:
1. 如果某个位置参数有默认值,那么从这个位置往后,从左向右,必须都要有默认值
2. 如果函数声明有默认值,函数实现的时候就不能有默认参数
函数占位参数
1、占位参数必须填补
函数重载
作用:函数名可以相同,提高复用性
函数重载条件
1、函数重载都需要在同一个作用域下
2、函数名字相同
3、函数参数类型不同/参数个数不同/参数顺序不同
4、返回值不同的函数不是函数重载
void Func_funcReloadTest()
{
cout << "func 的调用!" << endl;
}
void Func_funcReloadTest(int a)
{
cout << "func (int a) 的调用!" << endl;
}
void Func_funcReloadTest(double a)
{
cout << "func (double a)的调用!" << endl;
}
void Func_funcReloadTest(int a, double b)
{
cout << "func (int a ,double b) 的调用!" << endl;
}
void Func_funcReloadTest(double a, int b)
{
cout << "func (double a ,int b)的调用!" << endl;
}
//函数返回值不可以作为函数重载条件
//int func(double a, int b)
//{
// cout << "func (double a ,int b)的调用!" << endl;
//}
void Func_funcReload()
{
Func_funcReloadTest();
Func_funcReloadTest(10);
Func_funcReloadTest(3.14);
Func_funcReloadTest(10, 3.14);
Func_funcReloadTest(3.14, 10);
}
函数重载注意事项
1、引用作为重载条件
2、函数重载碰到函数默认参数
*/
//引用作为重载条件
void Func_funcReloadTest_Attention01(int &a)
{
cout << "func (int &a) 调用 " << endl;
}
void Func_funcReloadTest_Attention01(const int &a)
{
cout << "func (const int &a) 调用 " << endl;
}
//函数重载碰到函数默认参数 ,会出现二义性,避免
void Func_funcReloadTest_Attention02(int a, int b = 10)
{
cout << "func (int a, int b = 10) 调用 " << endl;
}
void Func_funcReloadTest_Attention02(int a)
{
cout << "func (int a) 调用 " << endl;
}
void Func_funcReload()
{
int a = 34;
Func_funcReloadTest_Attention01(a); //调用的是 非const 的函数
Func_funcReloadTest_Attention01(34); //调用的是 加const 的函数
//Func_funcReloadTest_Attention02(10);//err,函数重载碰到默认参数会出现二义性,尽量避免
Func_funcReloadTest_Attention02(67,57);//OK
}