c++中关于默认值的设置

测试代码:

$ cat test4.cpp
#include <iostream>

using namespace std;

void func(int a, int b, int c = 10);
void func2(int a, int b, int c);

int main(int argc, char *const argv[])
{
    func(1, 2);
    func(1, 2, 3);

    func2(1, 2); //oops !!!!!
    func2(1, 2, 3);
    return 0;
}

void func(int a, int b, int c)
{
    cout << "a: " << a << ", b: " << b << ", c: " << c << endl;
}

void func2(int a, int b, int c = 10)
{
    cout << "a: " << a << ", b: " << b << ", c: " << c << endl;
}

环境信息:

$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/local/gcc-5.5.0/libexec/gcc/x86_64-unknown-linux-gnu/5.5.0/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with: ../configure -enable-checking=release -enable-languages=c,c++ -disable-multilib --prefix=/usr/local/gcc-5.5.0
Thread model: posix
gcc version 5.5.0 (GCC)

编译:

$ g++ -std=c++11 test4.cpp
test4.cpp: In function ‘int main(int, char* const*):
test4.cpp:13:15: error: too few arguments to function ‘void func2(int, int, int)func2(1, 2); //oops !!!!!
               ^
test4.cpp:6:6: note: declared here
 void func2(int a, int b, int c);

总结:
(1)默认值尽可能在函数声明处定义。这样调用者也能及时看到。
(2)如果函数声明时,某一形参未指定默认值,而在定义时指定,调用函数时必须给这个形参传值(等于默认参数没用),否则将会报错:too few arguments to function。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值