C++笔记5--默认参数(default parameters)

来源:互联网 发布:淘宝上买快手粉丝 编辑:程序博客网 时间:2024/06/03 16:32

C++笔记5--默认参数(default parameters)

                                                                                                                              声明:本文档由王桂林老师编写的C++课件,经整理而出。


通常情况下,函数在调用时,形参从实参那里取得值。对于多次调用用一函数同一实参时,

C++给出了更简单的处理办法。给形参以默认值,这样就不用从实参那里取值了。


单个参数

#include <iostream>#include <ctime>using namespace std;void weatherForcast(const 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;}


规则
1.默认的顺序,是从右向左,不能跳跃。
2.函数声明和定义一体时,默认认参数在定义(声明)处。声明在前,定义在后,默认参数在声明处。
3.一个函数,不能既作重载,又作默认参数的函数。当你少写一个参数时,系统无法确认是重载还是默认参数

0 0
原创粉丝点击