c++提供给函数的参数设置默认参数,即在调用函数时 不给对应置位的参数传参时,该形参会使用默认参数,否则使用实参。
下面利用简单的自定义debug函数进行学习。 (下面代码中注释很重要)
先对默认参数 总结:
1. 必须从右向左进行设置 默认参数。
2. 默认参数不能同时出现在 函数的声明和实现中。
#include <iostream>
//默认参数:必须从右边开始设置默认参数
/* c++里面,参数里面不能char *str="hello", 需要 const char *str="hello"
默认参数只能出现在函数声明或者实现,但是又不能同时出现在 函数的声明和实现中。
*/
//报错,因为默认参数不能同时出现在 函数的声明和实现中
#if 0
void debug(int flag, const char* str="===========");
int main(){
debug(0);
}
void debug(int flag, const char* str="==========="){
std::cout << flag <<" : "<< str << std::endl;
}
#endif
#if 0
void debug(int flag, const char* str);
int main(){
debug(1);
}
void debug(int flag, const char* str="==========="){
std::cout << flag <<" : "<< str << std::endl;
}
#endif
#if 1
void debug(int flag, const char* str="===========");
int main(){
debug(2);
}
void debug(int flag, const char* str){
std::cout << flag <<" : "<< str << std::endl;
}
#endif
若使用debug(0)所在的程序,会报以下错误:default argument given for parameter ....
使用debug(2)所在的程序,编译时就没有报错。