Bit-fields “In-class initialization” results in “error: lvalue required as left operand of assignment”

南笙酒味 提交于 2019-11-27 04:44:58

问题


struct bitfield {
  int i = 0;  // ok
  int j : 8 = 0;  // error: lvalue required as left operand of assignment
};

What is the correct syntax to initialize bit-fields using C++11 "in-class initialization" feature?


回答1:


What is the correct syntax to initialize bit-fields using C++11 "in-class initialization" feature?

You cannot initialize bit-fields in-class. Paragraph 9.2 of the C++11 Standard specifies the grammar for class member declarators:

[...]

member-declarator:

declarator virt-specifier-seq(opt) pure-specifier(opt)

declarator brace-or-equal-initializer(opt)

identifier(opt) attribute-specifier-seq(opt): constant-expression

As you can see, declarators for bit-field members cannot be terminated by a brace-or-equal-initializer.




回答2:


This was raised as Core Issue 1341 to the C++ standard, but was rejected by the C++ Core Working Group in October 2015 as NAD ("not a defect") - see http://open-std.org/JTC1/SC22/WG21/docs/cwg_closed.html#1341




回答3:


You cannot (in C++11) in-class initialize bitfields.

In MSVC and gcc (with extensions), the anonymous union and struct code lets you get around this a bit.

struct bitfield {
  int i = 0;  // ok
  union {
    uint32_t raw = 0;
    struct {
      int j : 8;
      int x : 3;
    };
  };
};

where we mix a fixed size raw with a union over bitfields, then in-class initialize the raw element.




回答4:


You can write a constructor with initializer list to give default values to your bitfields.

struct bitfield {
  int i;
  int j : 8;

  bitfield() : i(0), j(0) {};
};

You can also create read-only fields with default values.

struct _UserRegister1
{
  uint8_t _RES0 : 1;
  const uint8_t reserved1 : 1;
  uint8_t _HTRE : 1;
  const uint8_t reserved2 : 3;
  uint8_t _VDDS : 1;
  uint8_t _RES1 : 1;

  _UserRegister1() : reserved1(1), reserved2(7) {};
};


来源:https://stackoverflow.com/questions/16520701/bit-fields-in-class-initialization-results-in-error-lvalue-required-as-left

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!