如何在 C 中访问联合内部的结构成员? [英] How to access a struct member inside a union in C?

查看:41
本文介绍了如何在 C 中访问联合内部的结构成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下联合:

union employee
{
    char key;

    struct manager
    {
        short int age;
        float shares;
        short int level;
    };

    struct worker
    {
        short int age;
        short int skill;
        short int department;
    };

} company[10];

如何访问联合 employee 内部结构的成员?我尝试通过这种方式访问​​ manager 结构的 age 成员:

How can I access a member of a structure which is inside the union employee? I tried to access the age member of the manager structure this way:

company[i].manager.age

但我收到 error C2039: 'manager' : is not a member of 'employee'.

推荐答案

在标签声明后添加一些内容.也许:

Add something after the tag declaration. Perhaps:

struct manager
{
    short int age;
    float shares;
    short int level;
} manager;

<小时>

旁注:您没有使用工会权利.关键,即告诉您是在与经理打交道还是与单纯的工人打交道的字段应该在一个封闭的对象中,在工会之外.也许:

struct employee {
    char key;

    union {
        struct manager ...;
        struct worker ...;
    } u;
};

正如 dasblinkenlight 所述,您可以在工会之外声明您的经理/工人标签.

As dasblinkenlight notes, you could declare your manager / worker tags outside the union.

这篇关于如何在 C 中访问联合内部的结构成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆