测试代码:
$ 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。