【问题标题】:Structure variable initialization in short way [duplicate]简短的结构变量初始化[重复]
【发布时间】:2021-09-04 10:40:27
【问题描述】:

尝试用简短的方式初始化结构变量字段:

typedef struct
{
    int id = 0;
    char* name = "none";
}employee;

employee e = 
{
    .id = 0 ;
    .name = "none" ;
};

e 初始化出错:

Error    expected ‘}’ before ‘;’ token                                                  
Note     to match this ‘{’                                                              
Error    could not convert ‘{0}’ from ‘<brace-enclosed initializer list>’ to ‘employee’ 

为什么会出现错误以及如何解决此问题?

【问题讨论】:

    标签: c struct initialization declaration


    【解决方案1】:

    在 C 中,您不能在结构定义中初始化数据成员。所以你必须写

    typedef struct
    {
        int id;
        char* name;
    }employee;
    

    列表初始化中的分隔符也是逗号。

    employee e = 
    {
        .id = 0,
        .name = "none",
    };
    

    employee e = 
    {
        .id = 0,
        .name = "none"
    };
    

    【讨论】:

    • 也许你应该补充一点,他可以在定义该类的变量时设置初始值
    • @DusanTodorovic 它是 C。没有课程。
    • 编译器对 typedef struct { int id = 0; char* name = "none"; }employee; 很满意,但以错误 could not convert ‘{0, "none"}’ from ‘&lt;brace-enclosed initializer list&gt;’ to ‘employee’ 响应 employee e = { .id = 0, .name = "none" };
    • @vico 表示你正在将程序编译为C++程序。
    • @0___________ 我想输入结构。错字
    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    相关资源
    最近更新 更多