具有基于位置的枚举编译错误的结构

问题描述 投票:2回答:1

这个:

enum Id {
    START,
    INDENT
};

struct State {
    int line;
    int column;
    Id id;
};

...

lexer::State state = {0};

编译。

但如果我把Id id作为结构的第一个元素,它就会停止。有人可以简单地向我解释为什么这两种结构被区别对待。

c++ struct enums
1个回答
4
投票

你得到一个错误,因为int类型的常量零与id类型的初始字段Id不兼容,除非

1)你添加一个演员,像这样

lexer::State state = {static_cast<Id>(0)};

2)或使用START代替零,像这样

lexer::State state = {START};

3)或零下降值初始化整个struct(推荐):

lexer::State state = {};
© www.soinside.com 2019 - 2024. All rights reserved.