错误:非法转换:从'int'到'union'

ven*_*914 1 c++ casting unions data-structures

我收到错误,illegal cast: from 'int' to 'FIELDS'同时在这里初始化结构变量: -

SOCKET_LOG_DATA socket_log_data() : fields(0), socket_number(0) {}
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

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;
Run Code Online (Sandbox Code Playgroud)

给了很多错误: -

".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 ;
Run Code Online (Sandbox Code Playgroud)

然后我socket_log_data()通过将行更改为保留构造函数

SOCKET_LOG_DATA socket_log_data() : fields{{0, 0}}, socket_number(0) {}
Run Code Online (Sandbox Code Playgroud)

,并收到以下错误: -

".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
Run Code Online (Sandbox Code Playgroud)

Die*_*Epp 5

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

: fields(0)
Run Code Online (Sandbox Code Playgroud)

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

: fields{{0, 0}}
Run Code Online (Sandbox Code Playgroud)

构造函数也有些可疑:

SOCKET_LOG_DATA socket_log_data() ...
Run Code Online (Sandbox Code Playgroud)

通常,它只是:

SOCKET_LOG_DATA() ...
Run Code Online (Sandbox Code Playgroud)