c++ - 如何使用具有默认值的参数制作函数原型(prototype)?

标签 c++

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/

相关文章:

c++ - 如何改变 boost::variant operator < 的行为

c++ - 将 mp4 解码为原始帧 Windows C++

c++ - 使用 Rcpp 运行已编译的 C++ 代码

c++ - C++ 中 <Pointer, String> 的 unordered_map

c++ - 为 x64 平台编译时出现 c2593 错误(运算符标识符不明确)

c++ - 符号的 ASCII 定义

c++ - 如何多次顺序调用3个线程?

c++ - 请帮我找出为什么我陷入无限循环?

c++ - BGL : specialization of template in different namespace

c++ - 计算表示稀疏 vector 的 map 之间的距离 C++