缺省参数
在C语言中,函数没有指定参数列表时,默认可以接收任意多个参数;
在C++中,因为有严格的参数类型检测,所以,函数没有参数列表时,默认为void,不接收任何参数。
以下是例子:
C++中:
#include<iostream>
using namespace std;
void Test()
{}
int main()
{
Test(10);
Test(10, "hello world");
return 0;
}
结果:
C语言:
#include<stdlib.h>
void Test()
{}
int main()
{
Test(10);
Test(10, "hello world");
return 0;
}
结果:
· 缺省参数概念:
(1)缺省参数是声明或定义函数时为函数的参数指定一个默认值 ;
(2)在调用该函数时,如果没有指定实参则采用该默认值,否则使用指定的实参。
#include<iostream>
using namespace std;
void Test(int a = 0)
{
cout << a << endl;
}
int main()
{
Test(); //没有传参时,使用参数默认值,则输出结果为0;
Test(10); //传参时,使用给定的参数,则输出结果为10.
system("pause");
return 0;
}
· 缺省参数的分类:
(1)全缺省参数:函数的每个参数都有缺省值,传参时,可传任意多个参数,且参数的传参是从左依次往右进行;
#include<iostream>
using namespace std;
void Test(int a = 0,int b = 0,int c = 0)
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
}
int main()
{
Test();
Test(10);
Test(10, 20);
Test(10, 20, 30);
return 0;
}
结果如下:
(2)半缺省参数:函数的部分参数有缺省值,且缺省值要从右往左依次给。
#include<iostream>
using namespace std;
void Test(int a, int b = 0, int c = 0)
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
}
int main()
{
//Test(); //编译时会出错,因为a没有缺省值,所以必须传参。
Test(10);
Test(10, 20);
Test(10, 20, 30);
return 0;
}
结果:
注意:
· 带缺省值的参数必须放在参数列表的最后面;
· 缺省参数不能同时在函数声明和定义中出现,只能在其中一个出现;
· 缺省值必须是常量或者全局变量;
· C语言不支持。