C++缺省参数

1.缺省参数的意义

缺省参数就是C++设计出来对C语言函数定义的优化

#include <iostream>
using namespace std;

void Func(int a = 0)
{
	cout << a << endl;
}
int main()
{
	Func(); 
	Func(10); 
}

对于上面Func()来说,在主函数中没有给参数

但是在函数定义的时候有int a=0

那么a就为0去运行函数,

但如果给了参数

Func(10),那么a就等于10,

说白了就是你给我我就把原来有的丢掉用你给的,你要是不给我我就用我自己的。

这就是缺省参数。

2.全缺省和半缺省

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;
}

上面那个Func1就是全缺省,意思就是我这参数全都有值

下面那个Func2就是半缺省,意思就是我这有些参数有值有些没有值

3.注意事项

1.C++规定半缺省参数必须从右往左依次连续缺省,不能间隔跳跃给缺省值


void Func2(int a=10, int b, int c = 20)
{
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl << endl;
}

比如上述情况就是错的 

2.带缺省参数的函数调用,C++规定必须从左往右依次给实参,不能跳跃给实参。

#include <iostream>
using namespace std;

void Func(int a = 10,int b = 20,int c = 30)
{
	cout << a << b << c << endl;
}
int main()
{
	Func(,10,20); 
}

比如上述就是错误的 

3.函数声明和定义时,缺省参数不能在函数声明和定义中同时出现,规定必须函数声明给缺省值

#include <iostream>
using namespace std;
void Func(int a,int b,int c);

void Func(int a = 10,int b = 20,int c = 30)
{
	cout << a << b << c << endl;
}
int main()
{
	Func(30,10,20); 
}

比如上述就是错误的 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值