Error: illegal cast: from 'int' to 'union'

Error: illegal cast: from 'int' to 'union'

我在此处初始化结构变量时遇到错误,illegal cast: from 'int' to 'FIELDS':-

SOCKET_LOG_DATA socket_log_data() : fields(0), socket_number(0) {}

我该如何解决?

typedef PACKED struct PACKED_SUFFIX
{
      UINT16 loss_reason : 1;
      UINT16 unused : 15;
} LOSS_REASON;

typedef union PACKED_SUFFIX
{
      LOSS_REASON loss;
      UINT16 all_fields;
} FIELDS;

typedef PACKED struct PACKED_SUFFIX SOCKET_LOG_DATA
{
      FIELDS fields;
      UINT16 socket_number;

      // As per @Dietrich's & @crashmstrcomments:-
      SOCKET_LOG_DATA() : fields{{0, 0}}, socket_number(0) {}
} SOCKET_LOG_DATA;

给出了很多错误:-

".filename.h", line 183: error (dplus:1207): syntax error near }
".filename.h", line 183: error (dplus:1463): type expected in arg-declaration-clause
".filename.h", line 183: error (dplus:1263): identifier socket_number already declared
".filename.h", line 183: error (dplus:1376): function int socket_number(void) is not a member of class $incomplete SOCKET_LOG_DATA
".filename.h", line 183: error (dplus:1247): syntax error after fields, expecting (
".filename.h", line 183: error (dplus:1404): mem initializers only allowed for constructors
".filename.h", line 183: error (dplus:1247): syntax error after 0, expecting ;

然后我通过将行更改为

来保留 socket_log_data() 构造函数
SOCKET_LOG_DATA socket_log_data() : fields{{0, 0}}, socket_number(0) {}

,并收到以下错误:-

".filename.h", line 183: error (dplus:1272): member $incomplete SOCKET_LOG_DATA::fields used outside non-static member function
".filename.h", line 183: error (dplus:1125): int constant expected
".filename.h", line 183: error (dplus:1536): bitfields must be integral type
".filename.h", line 183: error (dplus:1247): syntax error after fields, expecting ;
".filename.h", line 183: error (dplus:1436): syntax error - declarator expected after }
".filename.h", line 183: error (dplus:1461): type expected for socket_number
".filename.h", line 183: error (dplus:1247): syntax error after ), expecting ;
".filename.h", line 186: error (dplus:1461): type expected for SOCKET_LOG_DATA

您正在用单个 int 初始化 union:

: fields(0)

您可以像这样初始化第一个联合成员,而不是:

: fields{{0, 0}}

构造函数也有问题:

SOCKET_LOG_DATA socket_log_data() ...

通常情况下,它只是:

SOCKET_LOG_DATA() ...

相关查询

我通过正确的构造函数初始化和成员变量放置解决了这个问题,如下所示:-

typedef struct fields
{
    UINT16 loss_reason : 1;
    UINT16 unused : 15;
} FIELDS;

typedef union fields_union
{
    UINT16 all_fields;
    FIELDS ref_fields;
    fields_union() : all_fields(0), ref_fields() {}
} FIELDS_UNION;

typedef struct socket_log_data
{
    FIELDS_UNION ref_fields_union;
    UINT16 socket_number;
    socket_log_data() : socket_number(0), ref_fields_union() {}
} SOCKET_LOG_DATA;

感谢您的建议!