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)
这是避免处理数据的标准方法.
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)
这具有避免构造临时物体的优点.
小智 5
您可以使用花括号初始化:
myPreciousFunction(const std::string& s1 = {}, const std::string& s2 = {})
{
}
Run Code Online (Sandbox Code Playgroud)