目录
5.1 函数默认参数
语法:返回类型 函数名(参数=默认值){}
注意事项:
如果某个位置已经有了默认参数,那么从这个位置往后,从左到右都必须有默认值。
如果函数的声明有默认参数,函数实现就不能有默认参数。(编译器不知道用哪个参数)
5.2 函数占位参数
语法:返回类型 函数名(数据类型){} //(括号里只写数据类型,传递的参数类型必须和所写的一样)
void test1(int a, int)
{
cout << "func" << endl;
}
void test2(int a, int =10)//占位参数可以有默认参数
{
cout << "func" << endl;
}
5.3 函数重载
作用:函数名可以相同,提高复用性
满足条件:
①同一个作用域。(ex:都在全局作用域下)
②函数名称相同。
③参数类型不同/个数不同/顺序不同。
//在全局作用域
void test()
{
cout << "调用test( )" << endl;
}
void test(int a)
{
cout << "调用test(int a)" << endl;
}
void test(double a)
{
cout << "调用test(double a)" << endl;
}
void test(int a, int b)
{
cout << "调用test(int a, int b)" << endl;
}
void test(int a, double b)
{
cout << "调用test(int a, double b)" << endl;
}
void test(double a, int b)
{
cout << "调用test(double a, int b)" << endl;
}
int main()
{
test();
test(10);
test(3.14);
test(10,3.14);
test(3.14, 10);
return 0;
}
注意:函数的返回值不能作为函数重载的条件(返回值类型不同不行,有二义性)
引用作为函数重载的条件
//引用作为重载条件
void test(int &a)
{
cout << "调用test(int &a)" << endl;
}
void test(const int& b)
{
cout << "调用test(const int& b)" << endl;
}
int main()
{
int a = 10;
const int b = 10;
test(a);
test(b);
test(10);
return 0;
}
函数重载碰到默认参数
//函数重载碰到默认参数
void test(int a,int b=10)
{
cout << "调用test(int &a)" << endl;
}
void test(int a)
{
cout << "调用test(const int& b)" << endl;
}
int main()
{
test(10);//err,出现二义
return 0;
}