- 缺省参数是声明或定义函数时为函数的参数指定⼀个缺省值。在调⽤该函数时,如果没有指定实参 则采⽤该形参的缺省值,否则使⽤指定的实参,缺省参数分为全缺省和半缺省参数。(有些地⽅把 缺省参数也叫默认参数)
#include <iostream> #include <assert.h> using namespace std; void Func(int a = 0) { cout << a << endl; } int main() { Func(); // 没有传参时,使⽤参数的默认值 Func(10); // 传参时,使⽤指定的实参 return 0; }
- 全缺省就是全部形参给缺省值,半缺省就是部分形参给缺省值。
#include <iostream> using namespace std; // 全缺省 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; }
- C++规定半缺省参数必须从右往左 依次连续缺省,不能间隔跳跃给缺省值。
#include <iostream> using namespace std; // 半缺省 void Func2(int a = 10, int b, int c = 20) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl << endl; } int main() { Func2(100); Func2(100, 200); Func2(100, 200, 300); return 0; }
- 带缺省参数的函数调⽤,C++规定必须从左到右依次给实参,不能跳跃给实参。
#include <iostream> using namespace std; // 半缺省 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() { Func2(100); Func2(, 200); Func2(, 200, ); return 0; }
- 函数声明和定义分离时,缺省参数不能在函数声明和定义中同时出现,规定必须函数声明给缺省 值。
// 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); // 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; } // test.cpp #include"Stack.h" int main() { ST s1; STInit(&s1); // 确定知道要插⼊1000个数据,初始化时⼀把开好,避免扩容 ST s2; STInit(&s2, 1000); return 0; }



624

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



