c++ - 将字符串的填充构造函数与初始化列表一起使用

标签 c++ string

我正在通读 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 type std::initializer_list

所以 constructorstd::initializer_list 作为其第一个参数的 std::string 将始终在接受计数和字符的参数之前被考虑。

在此构造函数中使用列表初始化的唯一方法是同时提供分配器:

std::string s{6, 'z', std::string::allocator_type{}};

关于c++ - 将字符串的填充构造函数与初始化列表一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38918714/

相关文章:

c++ - 用于 makefie 构建的 C++ 程序的图形化免费调试器 (Windows XP)

c++ - 在 AIX 上使用 pthread 进行静态链接

java - 如何在android中使用加速度计跟踪路径?

regex - 使用 sed 捕获的组变量作为 bash 命令的输入

c++ - 构造函数中的空返回

c++ - 使用可能的 '\n' 符号从 istream 中读取

python - 在Python中格式化具有多个浮点值的字符串

javascript - 将字符串分成两部分,长度几乎相同

android - 关于 Android 公钥的说明?

c# - 在列表中查找单词存在的项目并忽略特殊字符