英文:
Curly Brace Initialisation with std::string
问题
我最近越来越多地使用花括号初始化。尽管我在这种情况下发现与圆括号初始化有所不同,我想知道为什么。
如果我这样做:
```c++
const std::string s(5, '=');
std::cout << s << std::endl;
我会得到:
=====
这是我预期的结果。但是如果我这样做:
const std::string s{5, '='};
std::cout << s << std::endl;
我会得到:
=
为什么会这样?
编辑:为了让看到这个的任何人受益,第二个输出中的 `=` 前面有一个不可打印的字符。它在stackoverflow上不显示。看起来像这样:
英文:
I have been using curly brace initialisation more and more recently. Although I found a difference to round bracket initialisation in this case and I was wondering why.
If I do:
const std::string s(5, '=');
std::cout << s << std::endl;
I get:
=====
This is what I expect. But if I do:
const std::string s{5, '='};
std::cout << s << std::endl;
I get:
=
Why is this?
Edit: For the benefit for anyone that sees this. There is an unprintable character before the =
in the second output. It just doesn't show on stackoverflow. Looks like:
答案1
得分: 5
这部分内容的翻译如下:
const std::string s(5, '=');
使用了接受_count_和字符_ch_(以及分配器)的构造函数:
constexpr basic_string(size_type count, CharT ch,
const Allocator& alloc = Allocator());
但是
const std::string s{5, '='};
使用了
constexpr basic_string(std::initializer_list<CharT> ilist,
const Allocator& alloc = Allocator());
这意味着5
将被转换为一个char
,因此你的字符串的大小将是2
。第一个字符将具有值5
,而另一个字符将是=
。
英文:
This
const std::string s(5, '=');
uses the constructor taking a count and the character, ch (as well as an allocator):
constexpr basic_string( size_type count, CharT ch,
const Allocator& alloc = Allocator() );
But
const std::string s{5, '='};
uses
constexpr basic_string( std::initializer_list<CharT> ilist,
const Allocator& alloc = Allocator() );
which means that 5
will be converted to a char
and your string will therefore have the size 2
. The first character will have the value 5
and the other will be =
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论