繁体   English   中英

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是一种比字符串的 char 数组最优雅、简洁和实用的方式,并且您将能够使用您想要的“C++”初始化形式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM