第一章C++对C的扩展(Externsion)--(5)默认参数
2015-11-12 14:07
471 查看
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);
相关文章推荐
- 第一章C++对C的扩展(Externsion)--(4)操作符重载
- 第一章C++对C的扩展(Externsion)--(3)函数重载
- 第一章C++对C的扩展(Externsion)--(2)输入与输出
- 关于C++ primer plus 第六章中文版 18.4
- 第一章 C++对C的扩展(Externsion)--(1)类型增强
- std::string的工具函数
- C语言输入终止
- C++ primer plus 第六版中文版 18.3
- 一个C++课程学习大纲
- #define 的用法解析
- 【转载】C/C++中const关键字详解
- C语言_用if```else语句解决奖金发放问题
- 赋值运算符函数的注意事项 ,指针和多维数组的讨论 (c/c++)
- 字典编码(C++实现)
- 基于C++中常见内存错误的总结
- C语言_IP地址解析
- C++ 构造函数和析构函数是否可以继承?
- C++ 构造函数和析构函数是否可以继承?
- 编译原理(二) NFA的确定化及DFA的最小化的算法及C++实现
- C++ primer plus 第六版中文版 18.2