zoukankan      html  css  js  c++  java
  • C++ struct 初始化的问题

    struct student

    {

        int age;

        string name;

        int id;

    };

    初始化:

    student st1={10, "li ming", 01};

    修改某个成员变量的值:st1.id = 11;

    下面谈我遇到的问题:id的接口准备好了,然而不知道name的值,也就是只需要把age和id进行设置就可以了

    已经存在的代码 const student st1 = {l_age};

    我需要将id计算出来并且添加进去,const student st1 = {l_age, l_id};//这是不对的,顺序初始化,没有对name进行初始化。顺序的缺陷是必须按成员定义的顺序逐个初始化,不能间隔。

    转到乱序初始化:

    student st1={ .age = 10,

                          .name = "li ming",

                          .id = 01};//C风格

    或者

    student st1={ age : 10,

                          name : "li ming",

                          id : 01};//C++ 风格

    但是gcc不支持后缀名为cpp的文件使用这种方式!!!!

    项目中是CPP后缀的文件,使用这种方式后编译提示sorry, unimplemented: non-trivial designated initializers not supported。
    最后解决办法:

    student st1 = {l_age};

    st1.id = l_id;

    虽然很ugly,只能等后面做name计算的团队去重构了,呵呵。

  • 相关阅读:
    169. Majority Element
    283. Move Zeroes
    1331. Rank Transform of an Array
    566. Reshape the Matrix
    985. Sum of Even Numbers After Queries
    1185. Day of the Week
    867. Transpose Matrix
    1217. Play with Chips
    766. Toeplitz Matrix
    1413. Minimum Value to Get Positive Step by Step Sum
  • 原文地址:https://www.cnblogs.com/hipposinsilt/p/6588608.html
Copyright © 2011-2022 走看看