1.缺省参数的意义
缺省参数就是C++设计出来对C语言函数定义的优化
#include <iostream>
using namespace std;
void Func(int a = 0)
{
cout << a << endl;
}
int main()
{
Func();
Func(10);
}
对于上面Func()来说,在主函数中没有给参数
但是在函数定义的时候有int a=0
那么a就为0去运行函数,
但如果给了参数
Func(10),那么a就等于10,
说白了就是你给我我就把原来有的丢掉用你给的,你要是不给我我就用我自己的。
这就是缺省参数。
2.全缺省和半缺省
void Func1(int a = 10, int b = 20, int c = 30)
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl << endl;
}
void Func2(int a, int b = 10, int c = 20)
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl << endl;
}
上面那个Func1就是全缺省,意思就是我这参数全都有值
下面那个Func2就是半缺省,意思就是我这有些参数有值有些没有值
3.注意事项
1.C++规定半缺省参数必须从右往左依次连续缺省,不能间隔跳跃给缺省值
void Func2(int a=10, int b, int c = 20)
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl << endl;
}
比如上述情况就是错的
2.带缺省参数的函数调用,C++规定必须从左往右依次给实参,不能跳跃给实参。
#include <iostream>
using namespace std;
void Func(int a = 10,int b = 20,int c = 30)
{
cout << a << b << c << endl;
}
int main()
{
Func(,10,20);
}
比如上述就是错误的
3.函数声明和定义时,缺省参数不能在函数声明和定义中同时出现,规定必须函数声明给缺省值
#include <iostream>
using namespace std;
void Func(int a,int b,int c);
void Func(int a = 10,int b = 20,int c = 30)
{
cout << a << b << c << endl;
}
int main()
{
Func(30,10,20);
}
比如上述就是错误的