定义:声明函数某个参数的时候指定一个默认值,调用该函数时如果采用默认值,无须指定该参数。
一般需要注意以下几点:
1.函数参数传递的顺序只能从前往后赋值,所以缺省参数默认值只能是从后向前给形参默认值。
Void func(int num = 0, float val); // 这种设置缺省参数的形式是错误的。
2.当调用函数时指定了缺省参数的值,则使用指定值覆盖默认值。
3.语法规定:在函数有声明的情况下,只能在函数声明中设置缺省参数,不能再定义中设置缺省参数,否则语法报错。
4.重载具有二义性,函数重载时需要明确指定参数,不能随意使用缺省参数,否则编译器会对参数不明确的函数调用报错。
5.函数的缺省参数不能重复设置。
#include <iostream>
using namespace std;
int add(int a, int b = 0, int c = 0)
{
return a + b + c;
}
// 语法规定:在函数有声明的情况下,只能在函数声明中设置缺省参数,不能再定义中设置缺省参数。
int func(int a = 1, int b = 2);
// 这种在函数定义中设置缺省参数的行为是错误的。
// int func(int a = 1, int b = 2)
int func(int a, int b)
{
cout << a + b << endl;
}
// 重载函数1
void print(int a = 1)
{
cout << a << endl;
}
// 相同的重载函数中不能重复设置缺省参数
/* void print(int a = 2)
{
cout << a << endl;
} */
// 重载函数2
void print()
{
int a = 1;
cout << a << endl;
}
int main()
{
// 函数缺省参数的基本用法
cout << add(10) << endl;
cout << add(10, 20) << endl;
cout << add(10, 20, 30) << endl;
// 在函数声明中设置缺省参数
func();
// 函数重载二义性造成编译语法报错
// 因为此时编译器无法识别使用带缺省参数的重载函数还是不带缺省参数的重载函数
// 解决方法要么传参,要么删掉其中一个重载函数
// print();
return 0;
}