C++中的struct char数组成员初始化
Struct char array member initialization in C++
我想了解 C++ 中的结构初始化,在特殊的 char 数组成员中:
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++ 不接受 (1) 形式?这将是最优雅、简洁和实用的方式。
考虑到(2)和(3),有更好的方法吗?
编辑 1:我选择放在这个问题中的代码已经过分简化。我的实际代码涉及结构中联合内的 char[] 成员。然后,std::string 不是一个选项。
只是替换
S s1={.x=12, .str = "Hello2"};
由'C'初始化表格
S s1={12, "Hello2"};
或者如备注中所述使用std::string
,这是比字符串数组最优雅、简洁和实用的方式,您将可以使用'C++'初始化形式你想要
我想了解 C++ 中的结构初始化,在特殊的 char 数组成员中:
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++ 不接受 (1) 形式?这将是最优雅、简洁和实用的方式。 考虑到(2)和(3),有更好的方法吗?
编辑 1:我选择放在这个问题中的代码已经过分简化。我的实际代码涉及结构中联合内的 char[] 成员。然后,std::string 不是一个选项。
只是替换
S s1={.x=12, .str = "Hello2"};
由'C'初始化表格
S s1={12, "Hello2"};
或者如备注中所述使用std::string
,这是比字符串数组最优雅、简洁和实用的方式,您将可以使用'C++'初始化形式你想要