☰
C++的缺省参数你了解嘛
2026/10/6 3:59:03 网站建设 项目流程

一、缺省参数概念

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

1

2

3

4

5

6

7

8

9

10

11

12

#include<iostream>

usingnamespacestd;

voidTestFunc(inta = 0)//参数缺省值

{

cout << a << endl;

}

intmain()

{

TestFunc();//没有指定实参,使用缺省值

TestFunc(10);//指定实参,使用实参

return0;

}

有什么用

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

#include<iostream>

usingnamespacestd;

namespaceWD

{

structStack

{

int* a;

intsize;

intcapacity;

};

}

usingnamespaceWD;

voidStackInit(structStack* ps)

{

ps->a = NULL;

ps->capacity = 0;

ps->size = 0;

}

voidStackPush(structStack* ps,intx)

{

if(ps->size == ps->capacity)

{

//ps->capacity *= 2;//err

ps->capacity == 0 ? 4 : ps->capacity * 2;//这里就必须写一个三目

}

}

voidStackInitCpp1(structStack* ps,intdefaultCP)

{

ps->a = (int*)malloc(sizeof(int) * defaultCP);

ps->capacity = 0;

ps->size = defaultCP;

}

voidStackInitCpp2(structStack* ps,intdefaultCP = 4)//ok

{

ps->a = (int*)malloc(sizeof(int) * defaultCP);

ps->capacity = 0;

ps->size = defaultCP;

}

intmain()

{

//假设明确知道这里至少需要100个数据到st1

structStack st1;

StackInitCpp1(&st1, 100);

//假设不知道st2里需要多少个数据 ———— 希望开小点

structStack st2;

StackInitCpp2(&st1);//缺省

return0;

}

二、缺省参数分类

全缺省参数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

voidTestFunc(inta = 10,intb = 20,intc = 30)

{

cout <<"a = "<< a << endl;

cout <<"b = "<< b << endl;

cout <<"c = "<< c << endl;

cout << endl;

}

intmain()

{

//非常灵活,

TestFunc();

TestFunc(1);

TestFunc(1, 2);

TestFunc(1, 2, 3);

//TestFunc(1, , 3);//err,注意它没办法实现b不传,只传a和b,也就是说编译器只能按照顺序传

return0;

}

注意:

全缺省参数只支持顺序传参

半缺省参数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

//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;}//void TestFunc(int a, int b = 10, /*int f, - err*/ int c = 20);//err,

voidTestFunc(inta,intb = 10,/*int f, int x = y, -> err*/intc = 20)

{

cout <<"a = "<< a << endl;

cout <<"b = "<< b << endl;

cout <<"c = "<< c << endl;

cout << endl;

}

intmain()

{

//TestFunc();//err,至少得传一个,这是根据形参有几个非半缺省参数确定的

TestFunc(1);

TestFunc(1, 2);

TestFunc(1, 2, 3);

return0;

}

1

//a.hvoid TestFunc(int a = 10);//a.cppvoid TestFunc(int a = 20){}

注意:

  • 半缺省参数必须从右往左依次来给出,且不能间隔着给
  • 缺省参数不能在函数声明和定义中同时出现
  • 缺省值必须是常量或者全局变量
  • C 语言不支持缺省


需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询