1.函数默认参数
//如果我们自己传入数据,就使用自己的数据,如果没有,那么用默认值
//如果某个位置参数有默认值,那么从这个参数往后,必须要有默认值
//如果函数声明有默认值,函数实现的时候就不能有默认参数
#include <iostream>
using namespace std;
int func(int c, int a = 10, int b = 10);
int func(int c, int a, int b)
{
return c + a + b;
}
int main()
{
cout << func(20) << endl;
cout << func(20, 30) << endl;
cout << func(20, 30, 30) << endl;
system("pause");
return 0;
}
2.函数的占位参数
语法:返回类型 函数名 (数据类型){}
#include <iostream>
using namespace std;
void func(int, int, int)
{
cout << "hello" << endl;
}
int main()
{
func(1,2,3);
system("pause");
return 0;
}
3.函数重载
作用:函数名可以相同,提高复用性
函数重载满足条件:
- 同一个作用域下
- 函数名称相同
- 函数参数类型不同,或者个数不同或者顺序不同
注意:函数的返回值不可以作为函数重载的条件
#include <iostream>
using namespace std;
void func()
{
cout << "hello" << endl;
}
int func(int a)
{
cout << a << endl;
return 0;
}
int main()
{
func();
func(2);
system("pause");
return 0;
}
4.函数重载的注意事项
- 引用作为重载条件
#include <iostream>
using namespace std;
void func(int& a)
{
cout << "hello" << endl;
}
int func(const int& a)
{
cout << "world" << endl;
return 0;
}
int main()
{
int a = 10;
const int b = 10;
func(a);
func(b);
func(10);
system("pause");
return 0;
}
- 函数重载碰到默认参数
#include <iostream>
using namespace std;
void func(int a)
{
cout << "hello" << endl;
}
int func(int a,int b=10)
{
cout << "world" << endl;
return 0;
}
int main()
{
func(10);
system("pause");
return 0;
}
//有问题,出现二义性,尽量避免