C ++-具有std :: string的统一初始化程序 [英] C++ - Uniform initializer with std::string

查看:319
本文介绍了C ++-具有std :: string的统一初始化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C ++的字符串类的统一初始化器.下面是代码:

I am trying the uniform intializer with the string class of C++. Below is the code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str1 {"aaaaa"};
    string str2 {5, 'a'};
    string str3 (5, 'a');

    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << "str3: " << str3 << endl;

    return 0;
}

输出为:

str1: aaaaa
str2: a
str3: aaaaa

这使我挠头.为什么str2无法获得str3的预期结果?

This made me scratched my head. Why str2 cannot achieved the desired result as str3?

推荐答案

具有一个采用initializer_list参数的构造函数.

std::string has a constructor that takes an initializer_list argument.

basic_string( std::initializer_list<CharT> init,
              const Allocator& alloc = Allocator() );

当您使用 braced-init-list 构造std::string时,该构造函数始终优先.仅当 braced-init-list 中的元素不能转换为initializer_list中的元素类型时,才考虑其他构造函数. [over.match.list]/1 中对此进行了提及.

That constructor always gets precedence when you use a braced-init-list to construct std::string. The other constructors are only considered if the elements in the braced-init-list are not convertible to the type of elements in the initializer_list. This is mentioned in [over.match.list]/1.

最初,候选函数是类T的初始化器列表构造函数([dcl.init.list]),参数列表由作为单个参数的初始化器列表组成.

Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T and the argument list consists of the initializer list as a single argument.

在您的示例中,第一个参数5可隐式转换为char,因此initializer_list构造函数是可行的,并且可以选择.

In your example, the first argument 5 is implicitly convertible to char, so the initializer_list constructor is viable, and it gets chosen.

如果将字符串中的每个字符都打印为int s

This is evident if you print each character in the strings as ints

void print(char const *prefix, string& s)
{
    cout << prefix << s << ", size " << s.size() << ": ";
    for(int c : s) cout << c << ' ';
    cout << '\n';
}

string str1 {"aaaaa"};
string str2 {5, 'a'};
string str3 (5, 'a');

print("str1: ", str1);
print("str2: ", str2);
print("str3: ", str3);

输出:

str1: aaaaa, size 5: 97 97 97 97 97 
str2: a, size 2: 5 97 
str3: aaaaa, size 5: 97 97 97 97 97 

实时演示

这篇关于C ++-具有std :: string的统一初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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