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

后端 未结 4 1000
难免孤独
难免孤独 2020-12-06 16:29
struct bitfield {
  int i = 0;  // ok
  int j : 8 = 0;  // error: lvalue required as left operand of assignment
};

What is the correct syntax to in

4条回答
  •  生来不讨喜
    2020-12-06 16:53

    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) {};
    };
    

提交回复
热议问题