缺省参数
声明:发生在成员函数的重载中
有一些参数的值在每次调用函数时都相同,c++利用缺省值使书写变得简单(在编译时,缺省值有编译器自动插入)
规则:
1、函数的缺省值只能出现在函数的声明过程中,而不出现在定义体中**
void fun(int x=0,int y=0);//正确,函数的缺省值出现在定义中
void fun(int x=0,int y=0) //错误,缺省值出现在定义中
{
......
}
#include<iostream>
using namespace std;
//声明
int Max(int a=0,int b=0);
//实现
int Max(int a,int b)
{
int c=a+b;
return c;
}
//c++忽略了返回值
void main()
{
Max(1,2);
//缺省值
Max();
}
原因:
1、函数的实现(定义)与参数有无缺省值无关
2、参数的缺省值需要修改时,修改声明,比修改函数定义方便
2、函数有多个参数时,从后往前挨个缺省
void fun(int x, int y=0,int z=0);//正确
void fun(int x=0, int y,int z=0);//错误
实例
#include<iostream>
using namespace std;
class Test
{
public:
//t(1)时,会出现错误
//void fun(int b=20,int c=30,int d);
// t(1) 出现二义性
//void fun(int b=0);
void fun(int b,int c=30,int d=20);
};
void Test::fun(int b,int c,int d)
{
cout<<b<<c<<d<<endl;
}
void main()
{
Test t;
t.fun(1); // 1 20 30
t.fun(1,2);// 1 2 30
t.fun(1,2,3);// 1 2 3
}
作用
1、为了使代码简洁
2、提高代码的利用性