缺省参数
缺省函数的概念
在定义或声明函数时,对函数的形参赋予了一个缺省值(默认值)。在调用函数时,如果没有指定实参,采用该函数的缺省值(默认值),否则使用指定实参。
#include<iostream>
using namespace std;
int at(int b=1)
{
return b;
}
int main()
{
cout << at() << endl;//没有实参时使用缺省值
cout << at(2) << endl;//有实参时使用实参
}
> 注意:
1.同名函数,在函数声明和定义时不可同时对形参赋予缺省值,只能对其中的一个赋予缺省值,因为在同名函数声明和定义时,如果恰巧给出了不同的缺省值,编译器不知道应该调用哪个缺省值。ps:在实际应用中一般在函数声明时赋予缺省值。
2. 缺省值必须是常量或者全局变量
缺省函数的分类
- 全缺省参数
函数的全部形参赋予缺省值
#include<iostream>
using namespace std;
int at(int a=1,int b=2,int c=3)
{
return a+b+c;
}
int main()
{
//函数实参需从左往右依次给出
at();
at(1);
at(1, 2);
at(1, 2, 3);
}
- 半缺省参数
函数的部分形参赋予缺省值, 使用半缺省必须从右往左依次来给出。
#include<iostream>
using namespace std;
int at1(int a, int b = 2, int c = 3)
{
return a + b + c;
}
int main()
{
at1(1);
at1(1, 2);
at1(1, 2, 3);
}