C ++结构初始化 [英] C++ Structure Initialization

查看:170
本文介绍了C ++结构初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用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


  1. C / C ++ for AIX

  2. C使用变量的结构初始化

  3. 使用C ++中的标记进行静态结构初始化

  4. C ++ 11正确的结构初始化

  1. C/C++ for AIX
  2. C Structure Initialization with Variable
  3. Static structure initialization with tags in C++
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆