**缺省参数是声明或定义函数时为函数的参数指定一个默认值。在调用该函数时,如果没有指定实参则采用该 默认值,否则使用指定的实参。**
void TestFunc(int a = 0)
{
cout << a << endl;
}
int main() {
TestFunc(); // 没有传参时,使用参数的默认值
TestFunc(10); // 传参时,使用指定的实参
}
当没有实参传入时候,缺少参数,输出为0,当实参为10,输出则为10.
缺省参数分类:
**全缺省参数
void Test(int a = 1, int b = 2, int c = 3)
{
cout << a <<" "<< b <<" "<< c<<endl;
}
int main()
{
Test();
Test(10);
Test(10,20);
Test(10, 20,30);
return 0;
}
分别输出:
**半缺省参数
void Test(int a , int b = 2, int c = 3)
{
cout << a <<" "<< b <<" "<< c<<endl;
}
int main()
{
Test(10);
Test(10,20);
Test(10, 20,30);
return 0;
}
***1. 半缺省参数必须从右往左依次来给出,不能间隔着给
2. 缺省参数不能在函数声明和定义中同时出现
3. 缺省值必须是常量或者全局变量
4. C语言不支持(编译器不支持)