gpt4 book ai didi

C++primer 第 5 篇关于 func 参数

转载 作者:行者123 更新时间:2023-11-30 05:21:05 26 4
gpt4 key购买 nike

它的问题是“给 make_plural (§ 6.3.2, p. 224) 的第二个参数一个默认参数 's'。通过打印单词 success 和 failure 的单数和复数版本来测试你的程序”这是 make_plural。

string make_plural(size_t ctr, const string& word, const string& ending )
{
return (ctr > 1) ? word + ending : word;
}

意思是改变'ending',但是ending是第三个参数,不是吗?这个问题让我很苦恼!问候!

最佳答案

这一定是打错了。

看代码:

string make_plural(size_t ctr, const string& word, const string& ending )
{
return (ctr > 1) ? word + ending : word;
}

最合理的做法是将“s”作为 ending 的默认值,因为这是默认情况下使用复数的方式(并非总是如此,但使用“bee”->“bees”例如它有效)。

一个更有力的论点是,如果第 (n+1) 个没有默认参数,则在 C++ 中不可能(除非您找到神奇的解决方法 (*))为第 n 个参数设置默认参数:

foo(int first = 0,int second) // not possible !!

对于这个例子,可能不太清楚为什么不允许这样做,但可以考虑使用多个默认值。比方说你会写:

foo(int first = 0,int second,int third = 0); // actually still not allowed

那么就没有办法知道是否

foo(1,2);

应该调用

foo(0,1,2); 

foo(1,2,0);

为了解决这种歧义,必须发明一些规则,对于 C++,规则是默认参数必须从右到左提供。

(*) 如果您可以更改功能并愿意编写一些额外的代码,则解决方法相当简单。您只需将所有参数封装在一个结构中,该结构提供使用您喜欢的任何默认值组合创建参数。

关于C++primer 第 5 篇关于 func 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40399647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com