Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++;-带有std::string的统一初始值设定项 我尝试用C++类的统一类整流器。代码如下: #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; }_C++_String_C++11_Uniform Initialization_List Initialization - Fatal编程技术网

C++;-带有std::string的统一初始值设定项 我尝试用C++类的统一类整流器。代码如下: #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; }

C++;-带有std::string的统一初始值设定项 我尝试用C++类的统一类整流器。代码如下: #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; },c++,string,c++11,uniform-initialization,list-initialization,C++,String,C++11,Uniform Initialization,List Initialization,这让我抓伤了头。当您使用此信号时,为什么str2无法达到所需的结果 std::basic_string( std::initializer_list<CharT> init, const Allocator& alloc = Allocator() ); 它将打印: Aa 请参阅另一个插图有一个构造函数,它接受一个初始值设定项列表参数 basic_string( std::initializer_list<CharT> init,

这让我抓伤了头。当您使用此信号时,为什么
str2
无法达到所需的结果

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

Aa
请参阅另一个插图

有一个构造函数,它接受一个
初始值设定项列表
参数

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

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++还是新手)。看来从现在起我得小心了。@Hilman,正如你所发现的,它并不总是那么一致地工作。例如,
向量v1{4,2},v2(4,2)。这里
v1
包含2个整数,4和2,而
v2
包含4个整数,每个整数初始化为2。
basic_string( std::initializer_list<CharT> init,
              const Allocator& alloc = Allocator() );
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