3.1函数默认参数
c++中,函数形参可以有默认值。
返回值类型 函数名 (参数 = 默认值)
{
}
# include<iostream>
using namespace std;
// 函数的默认参数
int func(int a, int b=10, int c=20) // 1、如果某个位置已经有了参数,那么从这个位置往后 从左到右都必须有默认值。
{
return a + b + c;
}
// 2、如果函数声明有默认参数,函数实现就不能有默认参数。
int func2(int a=10, int b=20);
int main() {
cout<<func(1, 2)<<endl; // 传值了用传的值,没传用默认值。
cout << func2() << endl;
system("pause");
return 0;
}
// 2、如果函数声明有默认参数,函数实现就不能有默认参数。
int func2(int a, int b)
{
return a + b;
}
3.2函数占位参数
# include<iostream>
using namespace std;
// 占位参数
// 返回值类型 函数名(数据结构){}
// 占位参数也可以有默认参数
void func(int a, int)
{
cout << "asd" << endl;
}
void func2(int a, int = 10)
{
cout << "asd" << endl;
}
int main() {
func(10, 10); // 要传对应的数据
system("pause");
return 0;
}
3.3函数重载
3.3.1函数重载概述
作用:函数名可以相同,提高复用性。
条件: 同一作用域下,函数名相同,函数参数类型不同、个数不同、顺序不同
函数的返回值不可以作为重载条件
# include<iostream>
using namespace std;
// 函数重载
void func()
{
cout << "函数重载" << endl;
}
void func(int a)
{
cout << "func(int a)函数重载" << endl;
}
void func(double a)
{
cout << "func(double a)函数重载" << endl;
}
int main() {
func();
func(1);
func(3.1415);
system("pause");
return 0;
}
3.3.2函数重载注意事项
引用作为重载条件
函数重载碰到函数默认参数
# include<iostream>
using namespace std;
// 函数重载 注意事项
//引用作为重载条件
void fun(int &a)
{
cout << "fun(int &a)" << endl;
}
void fun(const int& a)
{
cout << "fun(const int& a)" << endl;
}
//函数重载碰到函数默认参数
void fun2(int a,int b=10)
{
cout << "fun2(int a,int b)" << endl;
}
void fun2(int a)
{
cout << "fun2(int a)" << endl;
}
int main() {
int a = 10;
fun(a); // int &a = 10;不合法
fun(10); // const int &a=10; 合法(临时数据 指向 临时空间)
fun2(10); //函数重载 碰到 默认参数,出现二义性 报错,尽量避免这种情况
system("pause");
return 0;
}