错误:非法演员:来自' int'去工会'

时间:2016-02-18 15:19:58

标签: c++ data-structures casting unions

我在这里初始化结构变量时收到错误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

2 个答案:

答案 0 :(得分:5)

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

: fields(0)

您可以像这样初始化第一个联盟成员:

: fields{{0, 0}}

构造函数也有些可疑:

SOCKET_LOG_DATA socket_log_data() ...

通常,它只会是:

SOCKET_LOG_DATA() ...

答案 1 :(得分:1)

相关查询

http://stackoverflow.com/questions/35549540/identifier-int-not-a-direct-member-of-struct-socket-log-data/35555783#35555783

我通过适当的构造函数初始化和成员变量放置修复了这个问题,如下所示: -

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;

感谢您的建议!