如果编译器始终将对象视为匿名对象(无论是否命名该联合),为什么要命名一个联合呢?

我的实现如下所示:

typedef struct _DMessageHeader {
    union _msgId {
        unsigned char ucMsgId;
        unsigned short usMsgId;
        unsigned long ulMsgId;
        unsigned long long ullMsgId;
    } msgId;
} DMSG_HDR, *PDMSG_HDR;

我希望能够像这样访问它,但是编译器抛出错误:
PDMSG_DESC ptMsg->hdr.msgId = id_in;

它只允许我这样直接访问工会成员:
PDMSG_DESC ptMsg->hdr.msgId.ucMsgId = id_in;

关于这是为什么的任何想法,或者我如何通过名称访问工会?

最佳答案

我不确定在这种情况下为什么要使用工会。
请注意,在我的64位计算机上,该结构的大小为8个字节(long long的大小)。

#include <iostream>
using std::cout;
using std::endl;
typedef struct _DMessageHeader {
    union _msgId {
        unsigned char ucMsgId;
        unsigned short usMsgId;
        unsigned long ulMsgId;
        unsigned long long ullMsgId;
    }  msgId;
} DMSG_HDR, *PDMSG_HDR;

int main( int argc , char ** argv, char ** env)
{
    cout<<"sizof DMessageHeader"<<sizeof(DMSG_HDR)<<endl;
    return 0;
}

如果您存储在联合msgid中的所有文件都是一个不同长度(1-8)字节的单个ID,具体取决于您的体系结构),并且您没有任何存储约束,则按以下方式重写结构:
typedef struct _DMessageHeader {
unsigned long long msgId;
} DMSG_HDR, *PDMSG_HDR;
DMSG_HDR hdr;
hdr.msgId = id_in;

另外,我建议阅读this线程,以获取有关在C++中使用联合的全面讨论。

07-24 09:46
查看更多