C++ 默认字符串参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2749471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default string arguments
提问by John.M
myPreciousFunction(std::string s1 = "", std::string s2 = "")
{
}
int main()
{
myPreciousFunction();
}
Can i make the arguments look more pretty? I want there to be empty strings if no arguments were supplied.
我可以让论点看起来更漂亮吗?如果没有提供参数,我希望有空字符串。
回答by shoosh
you may consider this:
你可以考虑这个:
myPreciousFunction(std::string s1 = std::string(), std::string s2 = std::string())
{
}
But it doesn't really look prettier.
但它看起来并不漂亮。
Also, if you're passing strings, you might want to pass them as const&
:
此外,如果您要传递字符串,您可能希望将它们传递为const&
:
myPreciousFunction(const std::string& s1, const std::string& s2)
{
}
This is a standard way to avoid coping the data around.
这是避免处理周围数据的标准方法。
回答by Potatoswatter
There is actually another solution.
其实还有一个解决办法。
const std::string empty = std::string();
myPreciousFunction( const std::string &s1 = empty, const std::string &s2 = empty)
This has the advantage of avoiding construction of temporary objects.
这具有避免构造临时对象的优点。
回答by mdma
An alternative is to use overloaded functions, e.g.
另一种方法是使用重载函数,例如
myPreciousFunction(std::string s1, std::string s2)
{
// primary implementation
}
myPreciousFunction(std:string s1)
{
myPreciousFunction(s1, "");
}
myPreciousFunction()
{
myPreciousFunction("", "");
}
Though I'm not sure this is any prettier, and definitely less attractive code-wise. (Default arguments are there to avoid this.)
虽然我不确定这是否更漂亮,而且在代码方面绝对不那么有吸引力。(默认参数是为了避免这种情况。)
回答by Sasha Yakobchuk
You could use a braced initialisation:
您可以使用支撑初始化:
myPreciousFunction(const std::string& s1 = {}, const std::string& s2 = {})
{
}
回答by ericcurtin
You can use boost optional or std optional (C++17), that way you don't have to call the constructor of a string. This will give you truly optional arguments. These solutions are a default parameter of string ""
您可以使用 boost optional 或 std optional (C++17),这样您就不必调用字符串的构造函数。这将为您提供真正的可选参数。这些解决方案是字符串“”的默认参数
回答by Arrix
You can omit the namespace qualifier to make it look cleaner.
您可以省略命名空间限定符以使其看起来更简洁。
using namespace std;
void myPreciousFunction(string s1 = "", string s2 = "")
{
}