我正在通读 Ivor Horton's "Beginning C++" .在第 7 章中,有一个关于字符串初始化的例子:
However, you can initialize a string with any number of instances of given character. You can define and initialize a sleepy time
string
object like this:string sleeping {6, 'z'};
The
string
object,sleeping
, will contain"zzzzzz"
. The string length will be 6.
使用我的编译器 Apple LLVM version 6.0 (clang-600.0.57)
,示例无法按描述运行。相反,它就像我给出的那样工作:
string sleeping {"\6z"};
使用 string
's "from c-string" constructor, rather than its "fill" constructor .
我知道我可以通过使用括号来使用填充构造函数:
string sleeping(6, 'z');
但是为了满足我的好奇心,有没有办法像书中示例那样使用带有初始化列表的填充构造函数?
最佳答案
不,这是不可能的,标准specifies it :
- If
T
is an aggregate type [...];- Otherwise, if
T
is a character array [...];- If
T
is an aggregate type [...];- Otherwise, If the braced-init-list is empty [...];
- Otherwise, the constructors of
T
are considered, in two phases:
- All constructors that take
std::initializer_list
as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of typestd::initializer_list
所以 constructor以 std::initializer_list
作为其第一个参数的 std::string
将始终在接受计数和字符的参数之前被考虑。
在此构造函数中使用列表初始化的唯一方法是同时提供分配器:
std::string s{6, 'z', std::string::allocator_type{}};
关于c++ - 将字符串的填充构造函数与初始化列表一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38918714/