目录
缺省参数的概念
缺省参数是声明或定义函数时,给函数参数指定一个缺省值,在调用函数时,如果这个缺省参数没有指定实参则采用这个函数的缺省值作为参数,如果有指定实参,那么就用这个实参作为参数
看一个最容易理解的例子:
void func(int a = 1)
{
cout << "a=" << a << endl;
}
int main()
{
//没有传参时,使用缺省值参数
func();
//传参时,使用的是指定的实参
func(2);
return 0;
}
上面代码的函数就是缺省参数,第一次调用时因为没有给定实参,所以使用的是缺省值做参数,打印的是缺省值,第二次调用,用的是指定的实参,打印的是这个实参
缺省参数有两种
一种是全缺省,一种是半缺省(部分缺省)
全缺省参数
void func(int a = 1, int b = 2, int c = 3)
{
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl << endl;
}
int main()
{
func();
func(4);
func(4, 5);
func(4, 5, 6);
return 0;
}
全缺省参数,顾名思义就是每一个参数都指定一个缺省值。
半缺省参数
void func(int a, int b = 2, int c = 3)
{
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl << endl;
}
int main()
{
func(4);
func(4, 5);
func(4, 5, 6);
return 0;
}
注意:半缺省参数,缺省参数必须从右往左边依次指定给,不能隔着给。
半缺省参数,传参时,只能从左往右依次传,不能跳着、隔着传
声明或者定义函数时不能同时出现缺省参数
缺省值必须是常量或者全局变量
缺省参数错误使用的例子
缺省参数从左往右依次给
void func(int a = 1, int b = 2, int c)
{
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl << endl;
}
如果从左往右给缺省参数,编译是不能通过的,这个C++发明者规定的。
func(4);
而且还是有歧义的,如果只给一个实参4,那么编译器也无法确定是给第一个参数a传值,还是给第三个参数c传值。
缺省参数隔着给
void func(int a = 1, int b, int c = 3)
{
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl << endl;
}
传参时,跳着传
void func(int a = 1, int b = 2, int c = 3)
{
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl << endl;
}
func(, 5,);
函数定义和函数声明同时出现缺省参数
int fun(int a = 1, int b = 2, int c = 3);
void func(int a = 1, int b = 2, int c = 3)
{
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl << endl;
}
为什么要这样规定呢?这是为了防止声明的参数值和定义的参数值出现不一样的情况
比如:
int fun(int a = 1, int b = 2, int c = 3);
void func(int a = 4, int b = 5, int c = 6)
{
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl << endl;
}
编译时,编译器并不能确定要使用声明的缺省值还是要使用定义的缺省值。
函数重载
函数重载的概念
函数重载是函数的一种特殊情况,c++运行在同一作用域中声明功能类似的同名函数,这些同名函数的形参列表(参数个数,类型 或者 类型顺序)不同,常用来处理实现功能类似数据类型 不同的问题。
下面举例一些支持函数重载的例子
参数类型不同
//参数是int
int func(int a, int b)
{
return a + b;
}
//参数是double
double func(double a, double b)
{
return a + b;
}
参数个数不同
int func(int a, int b)
{
return a + b;
}
//参数个数不同
int func(int a, int b, int c)
{
return a + b + c;
}
参数类型顺序不同
int func(double a, int b)
{
return a + b;
}
//参数类型顺序不同
int func(int a, double b)
{
return a + b;
}