默认字符串参数

Joh*_*n.M 2 c++

myPreciousFunction(std::string s1 = "", std::string s2 = "")
{
}

int main()
{
    myPreciousFunction();
}
Run Code Online (Sandbox Code Playgroud)

我能让这些论点看起来更漂亮吗?如果没有提供参数,我希望有空字符串.

sho*_*osh 18

你可以考虑这个:

myPreciousFunction(std::string s1 = std::string(), std::string s2 = std::string())
{
}
Run Code Online (Sandbox Code Playgroud)

但它看起来并不漂亮.

此外,如果您传递字符串,您可能希望将它们传递为const&:

myPreciousFunction(const std::string& s1, const std::string& s2)
{
}
Run Code Online (Sandbox Code Playgroud)

这是避免处理数据的标准方法.

  • @John:你有一个有趣的可爱度量. (11认同)
  • 或者把它放在一起:`myPreciousFunction(const std :: string&s1 = std :: string(),const std :: string&s2 = std :: string())` (4认同)
  • 我将使用std :: string s1 = std :: string(),因为它看起来很棒! (2认同)

Pot*_*ter 11

实际上有另一种解决方案.

const std::string empty = std::string();

myPreciousFunction( const std::string &s1 = empty, const std::string &s2 = empty)
Run Code Online (Sandbox Code Playgroud)

这具有避免构造临时物体的优点.

  • @AbhishekMane你只需要在*和=之间有一个空格。问候,您友好的人类编译器。 (2认同)

小智 5

您可以使用花括号初始化:

myPreciousFunction(const std::string& s1 = {}, const std::string& s2 = {})
{
}
Run Code Online (Sandbox Code Playgroud)