myPreciousFunction(std::string s1 = "", std::string s2 = "")
{
}
int main()
{
myPreciousFunction();
}
我可以讓參數看起來更漂亮嗎? 如果沒有參數提供,我希望有空字符串。默認字符串參數
myPreciousFunction(std::string s1 = "", std::string s2 = "")
{
}
int main()
{
myPreciousFunction();
}
我可以讓參數看起來更漂亮嗎? 如果沒有參數提供,我希望有空字符串。默認字符串參數
你可以考慮這一點:
但它並沒有真正看起來更漂亮。
另外,如果你傳遞字符串,你可能想通過他們爲const&
:
myPreciousFunction(const std::string& s1, const std::string& s2)
{
}
這是爲了避免圍繞應對數據的標準方法。
您可以省略命名空間限定符以使其看起來更清晰。
using namespace std;
void myPreciousFunction(string s1 = "", string s2 = "")
{
}
命名空間對我來說很漂亮。 – 2010-05-01 10:10:45
由此填充全局名稱空間對於源文件是很好的,因爲沒有其他文件受此影響。 _But_:在頭文件中執行此操作將爲包含它的每個源文件和頭文件填充全局文件。它最終會導致問題。 – 2010-05-01 11:08:08
另一種方法是使用重載功能,例如,
myPreciousFunction(std::string s1, std::string s2)
{
// primary implementation
}
myPreciousFunction(std:string s1)
{
myPreciousFunction(s1, "");
}
myPreciousFunction()
{
myPreciousFunction("", "");
}
雖然我不知道這是任何漂亮,絕對的吸引力代碼明智。 (默認參數是有避免這種情況。)
實際上還有另一種解決方案。
const std::string empty = std::string();
myPreciousFunction(const std::string &s1 = empty, const std::string &s2 = empty)
這具有避免建造臨時物體的優點。
嗯,這是一個聰明的想法,不知道優化者會這樣做嗎?可能不是我猜。 – ericcurtin 2017-12-05 18:55:30
@ericcurtin不,但好奇的是編譯器允許對某些初始化列表進行優化。 – Potatoswatter 2017-12-05 20:19:58
您也可以使用boost可選或std可選(C++ 17),這樣您就不必調用字符串的構造函數。 – ericcurtin 2018-02-21 14:07:40
你可以使用一個支撐初始化:
myPreciousFunction(const std::string& s1 = {}, const std::string& s2 = {})
{
}
您可以使用可選的提升或std可選的(C++ 17),這樣你就不必調用一個字符串的構造函數。這會給你真正的可選參數。這些解決方案是默認參數字符串「」
你是什麼意思的「漂亮」 - 上面的代碼是默認參數的正確(且唯一)的語法。 – 2010-05-01 09:47:36
我想在參數中使用(string s1 = 0; string s2 = 0;)。 – 2010-05-01 09:54:19
爲什麼零「更漂亮」? – 2010-05-01 09:56:00