C ++ 11:string(50,'x')与string {50,'x'} [英] C++11: string(50, 'x') versus string{50, 'x'}

查看:231
本文介绍了C ++ 11:string(50,'x')与string {50,'x'}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ideone 所示:

  cout<< string(50,'x'); // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 
cout<< string {50,'x'}; // 2x

WAT ??



我发现50是ASCII'2',所以:

  cout< static_cast< int>('2'); // 50 
cout<< static_cast< char>(50); // 2

但是我已经有了。


解决方案

当你做

code> string {50,'x'} 你基本上用字符列表初始化字符串。



另一方面, string(50,'x')调用一个2参数构造函数,它被定义为重复 x 50次。 string {50,'x'} 不选择构造函数的原因是它可能是不明确的。如果你有一个三参数构造函数呢?如果类型有一个 initializer_list 构造函数,当你使用 {...} 进行初始化时, / p>

基本上你需要知道你的类型的构造函数。 initializer_list 构造函数总是有优先级,以避免歧义。


As seen on ideone:

cout << string(50, 'x'); // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
cout << string{50, 'x'}; // 2x

WAT??

I have figured out that 50 is ASCII '2', so:

cout << static_cast<int>('2'); // 50
cout << static_cast<char>(50); // 2

But that's as far as I've got.

Does this lead to a solid argument against C++11 initializers?

解决方案

When you do string { 50, 'x' } you're essentially initializing the string with a list of characters.

On the other hand, string(50, 'x') calls a 2 argument constructor, which is defined to repeat the character x 50 times. The reason why string { 50, 'x' } doesn't pick the constructor is that it could be ambiguous. What if you had a three parameter constructor as well? If the type has an initializer_list constructor, it will be picked when you use { ... } for initialization.

Basically you need to be aware of the constructors your type has. The initializer_list constructor will always have a precedence to avoid ambiguity.

这篇关于C ++ 11:string(50,'x')与string {50,'x'}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆