缺省参数概念
缺省参数是声明或定义函数时为函数参数指定一个默认值。在调用该函时,如果没有指定实参则采用该默认值,否则使用指定的实参。
先来看一段简单的代码:
void test(int c = 0)
{
cout << c << endl;
}
int main ()
{
test(); // 没有传参时,使用参数的默认值
test(100); // 传参时,使用指定的实参
}
结果:
第一个test函数中: 输出的结果是默认值0
第二个test函数中: 输出的结果是指定实参值10
缺省参数的分类
- 全缺省参数
void test(int a = 1, int b =2, int c =3)
{
cout << "a=" << a<<endl;
cout << "b=" << b<<endl;
cout << "c=" << c<<endl;
}
结果: 输出的全是默认值
总结: 全缺省时,所有的参数都是默认值,没有自己传参,编译器会使用默认参数列表中的参数
- 半缺省参数
void test(int a , int b =2, int c =3)
{
cout << "a=" << a<<endl;
cout << "b=" << b<<endl;
cout << "c=" << c<<endl;
}
int main()
{
test(); // 编译出错 不接受0个参数
test(1); // 可以编译, a = 1, b = 2, c =3
}
结果: test()编译出错,不接受0个参数 test(1) 可以编译,也有结果
总结: 这就可以说明 半缺省参数只能从右向左给出,实参中给的值在形参列表中从左向右匹配
void TestFunc1(int a =10; int b =20; int c = 30)
{
cout <<"a =";
cout <<"b =";
cout <<"c =";
}
int main ()
{
TestFunc1(); // 10 20 30
TestFunc1(1); // 1 20 30
TestFunc1(1,2); // 1 2 30
TestFunc1(1,2,3); // 1 2 3
}
总结: 半缺省参数是传参时只传了部分参数,那么会在形参列表中从左到右匹配
注意: 半缺省 只能从右往左缺省
注意:
- 半缺省参数必须从右往左依次来给出,不能间隔着跨着给出
- 缺省参数不能在函数声明和定义中同时出现
原因:因为如果生命周期与定义位置同时出现,恰巧两个位置提供的值不同,那么编译器就无法确定到底该用哪一个缺省值 - 缺省值是常量或者全局变量
- C语言不支持(编译器不支持)