简体   繁体   English

C++primer 5 关于func参数

[英]C++primer 5th about func parameter

Its question is" Give the second parameter of make_plural (§ 6.3.2, p. 224) a default argument of 's'. Test your program by printing singular and plural versions of the words success and failure" here is the make_plural.它的问题是“给 make_plural 的第二个参数(第 6.3.2 节,第 224 页)一个默认参数 's'。通过打印单数和复数版本的成功和失败来测试你的程序”这里是 make_plural。

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

Does it mean that change the 'ending', but ending is the third parameter, isn't it?这是否意味着更改“结尾”,但结尾是第三个参数,不是吗? This question worries me a lot!这个问题让我很担心! Regards!问候!

That must be a typo.那一定是笔误。

Looking at the code:查看代码:

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

the most reasonable thing would be to have "s" as default for ending , as this is how you make the plural by default (not always, but with "bee" -> "bees" eg it works).最合理的做法是将“s”作为ending默认值,因为这是默认情况下您如何制作复数(并非总是如此,但使用“bee”->“bees”,例如它有效)。

A much stronger argument is that in C++ it is not possible (unless you find a magic workaround (*)) to have a default argument for the n-th parameter if the (n+1)-th has no default argument:一个更有力的论据是,在 C++ 中,如果 (n+1)-th 没有默认参数,则不可能(除非您找到一种神奇的解决方法 (*))为第 n 个参数设置默认参数:

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

With this example it is maybe not so clear why this isnt allowed, but consider having multiple default values.在这个例子中,为什么不允许这样做可能不太清楚,但可以考虑使用多个默认值。 Lets say you would write:假设你会写:

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

Then there would be no way to know if那么就没有办法知道是否

foo(1,2);

is supposed to call应该打电话

foo(0,1,2); 

or或者

foo(1,2,0);

To resolve this ambiguity some rule had to be invented and for C++ the rule is that default arguments have to be provided from right to left.为了解决这种歧义,必须发明一些规则,对于 C++,规则是必须从右到左提供默认参数。

(*) If you can change the function and are willing to write some extra code, the workaround is rather trivial. (*) 如果您可以更改函数并愿意编写一些额外的代码,则解决方法相当简单。 You just have to encapsulate all parameters in a struct that provides creation of parameters with whatever combination of defaults you like.您只需将所有参数封装在一个结构中,该结构提供具有您喜欢的任何默认组合的参数的创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM