我是靠谱客的博主 欣喜小海豚,最近开发中收集的这篇文章主要介绍C++笔记5--默认参数(default parameters),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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.一个函数,不能既作重载,又作默认参数的函数。当你少写一个参数时,系统无法确认是重载还是默认参数

最后

以上就是欣喜小海豚为你收集整理的C++笔记5--默认参数(default parameters)的全部内容,希望文章能够帮你解决C++笔记5--默认参数(default parameters)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(225)

评论列表共有 0 条评论

立即
投稿
返回
顶部