首页IT科技c++缺省源(C++修炼之练气期第二层——缺省参数)

c++缺省源(C++修炼之练气期第二层——缺省参数)

时间2025-05-04 15:24:07分类IT科技浏览3063
导读:目录...

目录

1.缺省参数的概念

2.缺省参数的分类

全缺省参数

半缺省参数 

实用场景示例

1.缺省参数的概念

缺省参数是声明或定义函数时为函数的参数指定一个缺省值           。

在调用该函数时           ,如果没有指定实参则采用该形参的缺省值                ,否则使用指定的实参                。

#include <iostream> using namespace std; void F(int a = 0) { cout << "a = " << a << endl; } int main() { F();//未指定实参      ,使用参数的默认值 F(10);//传参时         ,使用指定的实参 return 0; }

2.缺省参数的分类

全缺省参数

void F(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() { F(100); F(100, 200); F(100, 200,300); //传参时                ,必须从左往右依次给 //错误示例: //F(100, ,300); return 0; }

半缺省参数 

void F(int a , int b , int c = 30) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; cout << endl; } int main() { F(100,200); F(100, 200, 300); return 0; }

注意:

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

//错误示例 void F(int a=10, int b, int c = 30) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; cout << endl; }

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

//错误示例 //test.cpp中定义 F(int a = 10); //test.h中声明 F(int a = 20); //编译器会报错

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

4. C语言不支持(编译器不支持)

实用场景示例

在之前数据结构的学习中      ,我们经常用到某个函数给来实现对某种数据结构的初始化(以栈为例);

struct Stack { int* a; int top; int capacity; }; void StackInit(struct Stack* ps) { int capacity = ps->capacity == 0 ? 4 : ps->capacity * 2; ps->a = (int*)malloc(sizeof(int) * capacity); if (ps->a == NULL) { perror("malloc fail"); return; } //... }

这样的写法有一个缺点                ,不管我们需要多大的空间            ,每次调用初始化函数时第一次都只能开辟4的空间   ,看着很呆板      。

但是运用缺省参数改进后:

void StackInit(struct Stack* ps, int defaultcapacity=4) { ps->a = (int*)malloc(sizeof(int) * defaultcapacity); if (ps->a == NULL) { perror("malloc fail"); return; } //... }

当我们想指定开辟多大空间时只需要多传一个参数就可以了                ,否则默认为4         。

当然除了这样的使用场景               ,缺省参数可以运用于很多很多场景,使得代码灵活性更高!

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
前端发送http请求(前端发送axios请求报错Request failed with status code 500解决方案)