ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

C++的缺省参数你了解嘛

C++的缺省参数你了解嘛 一、缺省参数概念缺省参数是声明或定义函数时为函数的参数指定一个默认值。在调用该函数时如果没有指定实参则采用该默认值否则使用指定的实参123456789101112#includeiostreamusingnamespacestd;voidTestFunc(inta 0)//参数缺省值{cout a endl;}intmain(){TestFunc();//没有指定实参使用缺省值TestFunc(10);//指定实参使用实参return0;}有什么用比如在 C 语言中有个很苦恼的问题是写栈时不知道要开多大的空间之前我们是如果栈为空就先开 4 块空间之后再以 2 倍走如果我们明确知道要很大的空间那么这样就只能一点一点的接近这块空间就太 low 了。但如果我们使用缺省明确知道不需要太大时就使用默认的空间大小明确知道要很大时再传参123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#includeiostreamusingnamespacestd;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;//errps-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个数据到st1structStack st1;StackInitCpp1(st1, 100);//假设不知道st2里需要多少个数据 ———— 希望开小点structStack st2;StackInitCpp2(st1);//缺省return0;}二、缺省参数分类全缺省参数1234567891011121314151617voidTestFunc(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;}注意全缺省参数只支持顺序传参半缺省参数12345678910111213141516//void TestFunc(int a, int b 10, /*int f, - err*/ int c 20);//errvoid 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);//errvoidTestFunc(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 语言不支持缺省
返回列表