Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.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+中的结构字符数组成员初始化+; 我试图理解C++中的结构初始化,在特殊字符数组成员: struct S { int x; char str[16]; }; // (1) This would be the desired way: simple and compact, but doesn't work S s1={.x=12, .str = "Hello2"}; // (2) Instead, this appears the correct way to do, but it is ugly and cumbersome for bigger strings S s2={.x=25, .str = {'H','e','l','l','o', '1'}}; // (3) This works too, easy to type, but uses 2 lines and a additional function (strcpy) S s3={.x=12}; strcpy(s3.str, "Hello3");_C++_Struct_Initialization - Fatal编程技术网

C+中的结构字符数组成员初始化+; 我试图理解C++中的结构初始化,在特殊字符数组成员: struct S { int x; char str[16]; }; // (1) This would be the desired way: simple and compact, but doesn't work S s1={.x=12, .str = "Hello2"}; // (2) Instead, this appears the correct way to do, but it is ugly and cumbersome for bigger strings S s2={.x=25, .str = {'H','e','l','l','o', '1'}}; // (3) This works too, easy to type, but uses 2 lines and a additional function (strcpy) S s3={.x=12}; strcpy(s3.str, "Hello3");

C+中的结构字符数组成员初始化+; 我试图理解C++中的结构初始化,在特殊字符数组成员: struct S { int x; char str[16]; }; // (1) This would be the desired way: simple and compact, but doesn't work S s1={.x=12, .str = "Hello2"}; // (2) Instead, this appears the correct way to do, but it is ugly and cumbersome for bigger strings S s2={.x=25, .str = {'H','e','l','l','o', '1'}}; // (3) This works too, easy to type, but uses 2 lines and a additional function (strcpy) S s3={.x=12}; strcpy(s3.str, "Hello3");,c++,struct,initialization,C++,Struct,Initialization,为什么现代C++不接受(1)形式?这将是最优雅、简洁和实用的方式。 考虑(2)和(3),有没有更好的方法来实现这一点 编辑1:我选择在这个问题中使用的代码过于简单。我的实际代码涉及结构中的联合中的char[]成员。然后,std::string不是选项只需替换即可 通过“C”初始化表单 S s1={12, "Hello2"}; 或者如备注中所述,使用std::string,这是一种比字符串的字符数组更优雅、简洁和实用的方法,你可以使用你想要的“C++”初始化形式,为什么 STR 不是一个 STD

为什么现代C++不接受(1)形式?这将是最优雅、简洁和实用的方式。 考虑(2)和(3),有没有更好的方法来实现这一点

编辑1:我选择在这个问题中使用的代码过于简单。我的实际代码涉及结构中的联合中的char[]成员。然后,std::string不是选项

只需替换即可

通过“C”初始化表单

S s1={12, "Hello2"};

或者如备注中所述,使用
std::string
,这是一种比字符串的字符数组更优雅、简洁和实用的方法,你可以使用你想要的“C++”初始化形式,为什么<代码> STR 不是一个<代码> STD::String ?C++中处理字符串的标准方法是使用<代码> STD::String < /C>。这个结构应该解决的实际问题是什么?为什么需要固定大小的阵列?如果不能摆脱数组,为什么不创建一个初始化数组的构造函数?“为什么现代C++不接受(1)形式?”因为现代C++(和老C++)使用了<代码> STD::String < /Cl>而不是字符数组。(1)代码在<代码> ClangCl< /Cl>和<代码> MSVC < /代码>中工作。(后者带有
/std:c++latest
-以便使用指定的初始值设定项)。我在这个问题中选择的代码过于简单。我的实际代码包含一个字符[]结构中的联合中的成员。我不能将std::string放入联合中。但它需要遵循成员字段的顺序。可以使用指示符(成员名称)在某种程度上,@ BKK781:是的,你必须像C一样处理命令,不,你不能使用指示符,因为只有C++表单允许这样做。我很好奇为什么C++委员会不包含这个简单的特性(允许使用标识符从文字字符串中初始化一个字符[])。
S s1={12, "Hello2"};