- 缺省参数的作用:
缺省参数是声明或定义函数时为函数的参数指定⼀个缺省值。在调⽤该函数时,如果没有指定实参则采⽤该形参的缺省值,否则使⽤指定的实参,缺省参数分为全缺省和半缺省参数。(有些地⽅把缺省参数也叫默认参数)
2.缺省参数的分类:
全缺省就是全部形参给缺省值,半缺省就是部分形参给缺省值。
常见的缺省参数的用法:
|
01 02 03 04 05 06 07 08 09 10 11 12 13 |
#include <iostream>
using namespace std; void Func(int a = 0) { cout << a << endl; } int main() { Func(); // 没有传参时,使⽤参数的默认值 Func(10); // 传参时,使⽤指定的实参 return 0; } |
分类如下
|
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// 全缺省 void Func1(int a = 10, int b = 20, int c = 30) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl << endl; } // 半缺省 void Func2(int a, int b = 10, int c = 20) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl << endl; } int main() { Func1(); Func1(1); Func1(1, 2); Func1(1, 2, 3); Func2(100); Func2(100, 200); Func2(100, 200, 300); return 0; } |
运行结果如下:
3.缺省参数的注意事项:
当缺省值出现间断赋值或从左往右赋值会出现报错。函数声明和定义分离时,缺省参数不能在函数声明和定义中同时出现,规定必须函数声明给缺省
值。
错误用例如下:
|
1 2 3 4 5 6 |
void Func2(int a = 20, int b = 10, int c ) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl << endl; } |
函数声明和定义分离时,缺省参数不能在函数声明和定义中同时出现,规定必须函数声明给缺省值。
用法如下:
|
01 02 03 04 05 06 07 08 09 10 11 12 |
// Stack.h #include <iostream> #include <assert.h> using namespace std; typedef int STDataType; typedef struct Stack { STDataType* a; int top; int capacity; }ST; void STInit(ST* ps, int n = 4); |
|
01 02 03 04 05 06 07 08 09 10 |
// Stack.cpp #include"Stack.h" // 缺省参数不能声明和定义同时给 void STInit(ST* ps, int n) { assert(ps && n > 0); ps->a = (STDataType*)malloc(n * sizeof(STDataType)); ps->top = 0; ps->capacity = n; } |
|
01 02 03 04 05 06 07 08 09 10 11 |
// test.cpp #include"Stack.h" int main() { ST s1; STInit(&s1); ST s2; STInit(&s2, 1000); return 0; } |
3285

被折叠的 条评论
为什么被折叠?



