例如,有3个文件,sum.h
, sum.cpp
, 和 main.cpp
.
sum.h
--
...
int sum (int, int, int);
...
sum.cpp
...
int sum (int a, int b, int c=10) {
return a + b + c;
}
main.cpp
...
cout << sum (1, 2) << endl;
...
编译器抛出一个错误说 too few arguments to function...
.
如果我编码为 cout << sum (1,2,3) << endl;
它工作正常
但是如何只传递 2 个参数呢?
默认函数参数必须放在调用站点看到的函数声明中。
int sum (int, int, int = 10);
它们在调用函数的表达式中是必需的。实现不应该关心它是否传递了默认值。
此外,您可以在更小的范围内重新声明函数,并给出完全不同的默认参数。此代码片段摘自 c++17 标准草案并演示了我的意思:
void f(int, int);
void f(int, int = 7);
void h() {
f(3); // OK, calls f(3, 7)
void f(int = 1, int); // error: does not use default
// from surrounding scope
}
void m() {
void f(int, int); // has no defaults
f(4); // error: wrong number of arguments
void f(int, int = 5); // OK
f(4); // OK, calls f(4, 5);
void f(int, int = 5); // error: cannot redefine, even to
// same value
}
void n() {
f(6); // OK, calls f(6, 7)
}
理论上(在实践中不要这样做),您甚至可以使用不同的 header 来声明具有不同默认参数值的相同函数。只要它们不包含在同一个翻译单元中,它就会按预期工作。