【C++】缺省参数

  • ​​​​概念:

缺省参数是声明或定义函数时为函数的参数指定一个默认值。在调用该函数时,如果没有指定实参则采用该默认值,否则使用指定的实参。

#include <iostream>

using namespace std;

using std::cout;
using std::endl;
void TestFunc(int a = 0)//缺省参数
{
	std::cout << a << std::endl;
}
int main()
{
	TestFunc();//不传参数时,就使用缺省的
	TestFunc(10);//传参时,使用指定的实参
}

分析:此时输出结果是 0

  • 分类:

  • 1.全缺省参数(所有参数全缺省)
void TestFunc(int a = 10,int b = 20,int c=30)//缺省参数
{
	std::cout << "a= "<< a<<std::endl;
	std::cout << "b= " << a << std::endl;
	std::cout << "c= " << a << std::endl;
}
int main()
{
	TestFunc();//输出结果为:10 20 30,都是缺省值
	TestFunc(1);//1 20 30
	TestFunc(1,2);//1 2 30
	TestFunc(1,2,3);//1 2 3
}

分析:上面就是全缺省的四种用法。全缺省的好处就是调用函数更多样化,如果你不想传参,就可以考虑用缺省,如果是全缺省,可以传1个参数,2个参数,3个参数,都不传参数也可以。

  • 2.半缺省参数(缺省部分参数)
void TestFunc(int a ,int b = 20,int c=30)//缺省两个参数
{
	std::cout << "a= "<< a<<std::endl;
	std::cout << "b= " << a << std::endl;
	std::cout << "c= " << a << std::endl;
}
int main()
{
	TestFunc(1);
	TestFunc(1,2);
	TestFunc(1,2,3);
}

void TestFunc(int a ,int b,int c=30)//缺省一个参数
{
	std::cout << "a= "<< a<<std::endl;
	std::cout << "b= " << a << std::endl;
	std::cout << "c= " << a << std::endl;
}
int main()
{
	TestFunc(1,2);
}

像这样缺省,是不行的:

void TestFunc(int a =10,int b ,int c=30)

这样缺省有一个歧义,如果传两个参数,不知道是传给前两个还是后两个,难以明确。这就要求缺省参数必须连续,并且得从右往左缺省,半缺省只能缺省右边的。

  • 注意事项:

1.半缺省参数必须从右往左依次来给出,不能间隔着给

2.缺省参数不能在函数声明和定义中同时出现

//a.h
void TestFunc(int a = 10);

// a.c
void TestFunc(int a = 20)

注意:如果声明与定义位置同时出现,恰巧两个位置提供的值不同,那编译器就无法确定到底该用那个缺省值。一般是在声明的时候出现,定义的时候不用给。也可以单独出现在定义中。

3.缺省值必须是常量或者全局变量

4. C语言不支持缺省参数(编译器不支持),这也是C语言和c++的一个区别吧!

猜你喜欢

转载自blog.csdn.net/qq_42270373/article/details/83895407