5.默认参数(default parameters)
通常情况下,函数在调用时,形参从实参那里取得值。对于多次调用用一函数同一实参时,C++给出了更简单的处理办法。给形参以默认值,这样就不用从实参那里取值了。
5.1.示例
单个参数
#include <iostream>
#include <ctime>
using namespace std;
void weatherForcast(char * w="sunny")
{
time_t t = time(0);
char tmp[64];
strftime( tmp, sizeof(tmp), "%Y/%m/%d %X %A ",localtime(&t) );
cout<<tmp<< "today is weahter "<<w<<endl;
}
int main()
{
//sunny windy cloudy foggy rainy
weatherForcast();
weatherForcast("rainny");
weatherForcast();
return 0;
}
多个参数
float volume(float length, float weight = 4,float high = 5)
{
return length*weight*high;
}
int main()
{
float v = volume(10);
float v1 = volume(10,20);
float v2 = volume(10,20,30);
cout<<v<<endl;
cout<<v1<<endl;
cout<<v2<<endl;
return 0;
}
5.2.规则
- 1 默认的顺序,是从右向左,不能跳跃。
- 2 函数声明和定义一体时,默认认参数在定义(声明)处。声明在 前,定义在后,默认参数在声明处。
- 3 一个函数,不能既作重载,又作默认参数的函数。当你少写一个参数时,系统 无法确认是重载还是默认参数。
void print(int a)
{
}
void print(int a,int b =10)
{
}
int main()
{
print(10);
return 0;
}
main.cpp:16: error: call of overloaded 'print(int)' is ambiguous
print(10);