1

背景:在处理时间时,我想在已知时将“现在”作为参数传递,并询问系统是否还不知道,所以我将它传递给默认调用时间函数的参数。这似乎适用于 GCC (4.1.2),如下面的代码所示(看起来有点奇怪,但随着时间的推移,示例往往会更复杂一些)。

问题:调用函数作为默认参数是否符合 C++ 标准/可移植/合理实践?
欢迎引用标准、链接和 SO 问题

#include <iostream>
#include <string>

std::string getString()
{
  std::cout << "Default: " << std::flush;
  char line[100];
  std::cin.getline(line, 100);
  return line;
}

void printString(const std::string& str = getString())
{
  std::cout << str << std::endl;
}

int main()
{
  printString("start");
  printString();
  printString("stop");
}
4

2 回答 2

4

是的,函数被允许作为默认参数。请参阅 2003 标准的 8.3.6/5 中的示例

于 2010-09-22T13:22:36.660 回答
4

C++ 编程语言(第 7.5 节)说:

"A default argument is type checked at the time of the function declaration and evaluated at the time of the call." (italics mine)

So it is OK to pass a function as the default argument.

于 2010-09-22T13:27:03.497 回答