A 有一个原型(prototype)为的函数:
void arryprnt(int[], string, int, string, string);
还有一个定义:
void arryprnt(int[] a, string intro, int len, string sep=", ", string end=".") {
// stuff
}
我这样调用它:
arryprnt(jimmy, "PSEUDOJIMMY: ", 15);
...当我调用 arryprnt 时,我收到一个编译器错误,说我使用的参数太少,这是基于原型(prototype)所说的。 “好吧,”我在想,“编译器不知道 arryprnt 的一些参数有默认值。我只是将参数从定义中复制到原型(prototype)中。”然而,我确实遇到了一个编译器错误,告诉我我正在用太多参数调用 arryprnt!我可以明确指定所有参数,但有没有办法在不指定所有参数的情况下调用它?
最佳答案
您应该将默认参数放在原型(prototype)中,而不是像这样的定义:
void arryprnt(int[] a, string intro, int len, string sep=", ", string end=".");
并在没有它们的情况下进行定义:
void arryprnt(int[] a, string intro, int len, string sep, string end) {
// ...
}
顺便说一句:另一个注意事项。通过const reference 传递大于 int 的对象被认为是一种很好的做法。虽然这并不适合所有 情况,但它适用于大多数情况并且避免了不必要的复制。例如:
void func(const std::string &s) {
// do some read-only operation with s.
}
func("hello world");
关于c++ - 如何使用具有默认值的参数制作函数原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/931195/