C++11: string(50, 'x') versus string{50, 'x'}

后端 未结 1 858
长发绾君心
长发绾君心 2021-01-05 11:47

As seen on ideone:

cout << string(50, \'x\'); // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
cout << string{50, \'x\'}; // 2x
相关标签:
1条回答
  • 2021-01-05 12:19

    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.

    0 讨论(0)
提交回复
热议问题