C ++结构初始化 [英] C++ Structure Initialization
问题描述
可以使用C ++初始化结构,如下所示
Is it possible to initialize structs in C++ as indicated below
struct address {
int street_no;
char *street_name;
char *city;
char *prov;
char *postal_code;
};
address temp_address =
{ .city = "Hamilton", .prov = "Ontario" };
链接此处和这里提到,可以只在C中使用这种风格。如果是这样为什么这不可能在C + +?是否有任何潜在的技术原因,为什么它不实现在C + +,或者是不好的做法,使用这种风格。我喜欢使用这种初始化方式,因为我的结构是大的,这种风格给我清楚的可读性分配给哪个成员的值。
The links here and here mention that it is possible to use this style only in C. If so why is this not possible in C++? Is there any underlying technical reason why it is not implemented in C++, or is it bad practice to use this style. I like using this way of initializing because my struct is big and this style gives me clear readability of what value is assigned to which member.
请与我分享,如果有
我在发布此问题之前引用了以下链接
I have referred the following links before posting this question
- C/C++ for AIX
- C Structure Initialization with Variable
- Static structure initialization with tags in C++
- C++11 Proper Structure Initialization
推荐答案
以清楚每个初始值设定值是什么,只是将它拆分成多行,并在每一行上加上注释:
If you want to make it clear what each initializer value is, just split it up on multiple lines, with a comment on each:
address temp_addres = {
0, // street_no
nullptr, // street_name
"Hamilton", // city
"Ontario", // prov
nullptr, // postal_code
};
这篇关于C ++结构初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!