【第1篇】c++ 默认参数

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)所在的程序,编译时就没有报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值