C++缺省参数

一、缺省参数概念

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

#include<iostream>
using namespace std;
void TestFunc(int a = 0)//参数缺省值
{
	cout << a << endl;
}
int main()
{
	TestFunc();//没有指定实参,使用缺省值
	TestFunc(10);//指定实参,使用实参
	return 0;
}

❗ 有什么用 ❕

比如在 C 语言中有个很苦恼的问题是写栈时,不知道要开多大的空间,之前我们是如果栈为空就先开 4 块空间,之后再以 2 倍走,如果我们明确知道要很大的空间,那么这样就只能一点一点的接近这块空间,就太 low 了。但如果我们使用缺省,明确知道不需要太大时就使用默认的空间大小,明确知道要很大时再传参

#include<iostream>
using namespace std;
namespace WD
{
	struct Stack
	{
		int* a;
		int size;
		int capacity;	
	};
}
using namespace WD;
void StackInit(struct Stack* ps)
{
	ps->a = NULL; 
	ps->capacity = 0;
	ps->size = 0;
}
void StackPush(struct Stack* ps, int x)
{
	if(ps->size == ps->capacity)
	{
		//ps->capacity *= 2;//err
		ps->capacity == 0 ? 4 : ps->capacity * 2;//这里就必须写一个三目
	}
}

void StackInitCpp1(struct Stack* ps, int defaultCP)
{
	ps->a = (int*)malloc(sizeof(int) * defaultCP);
	ps->capacity = 0;
	ps->size = defaultCP;
}
void StackInitCpp2(struct Stack* ps, int defaultCP = 4)//ok
{
	ps->a = (int*)malloc(sizeof(int) * defaultCP);
	ps->capacity = 0;
	ps->size = defaultCP;
}
int main()
{
	//假设明确知道这里至少需要100个数据到st1
	struct Stack st1; 
	StackInitCpp1(&st1, 100);
	//假设不知道st2里需要多少个数据 ———— 希望开小点
	struct Stack st2;  
	StackInitCpp2(&st1);//缺省
	return 0;
}

二、缺省参数分类

❗ 全缺省参数 ❕

void TestFunc(int a = 10, int b = 20, int c = 30)
{
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;
	cout << endl;
}
int main()
{
	//非常灵活,
	TestFunc();
	TestFunc(1);
	TestFunc(1, 2);
	TestFunc(1, 2, 3);	
	//TestFunc(1, , 3);//err,注意它没办法实现b不传,只传a和b,也就是说编译器只能按照顺序传
	return 0;
}

⚠ 注意:

  1️⃣ 全缺省参数只支持顺序传参

❗ 半缺省参数 ❕

//void TestFunc(int a, int b = 10, /*int f, - err*/ int c = 20);//err,

void TestFunc(int a, int b = 10, /*int f, int x = y, -> err*/ int c = 20)
{
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;
	cout << endl;
}
int main()
{
	//TestFunc();//err,至少得传一个,这是根据形参有几个非半缺省参数确定的
	TestFunc(1);
	TestFunc(1, 2);
	TestFunc(1, 2, 3);	
	return 0;
}
//a.h
void TestFunc(int a = 10);
//a.cpp
void TestFunc(int a = 20)
{}

⚠ 注意:

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

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

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

  4️⃣ C 语言不支持缺省

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>