如何使用联合以及两个结构+更多

时间:2015-02-19 00:11:32

标签: c struct unions

我的任务有问题,希望得到一些帮助。

我想有两个结构,志愿者和员工,以及一个以名字,姓氏,电话号码+志愿者或员工为结构的工会“人”。

我之前有过使用工会+结构的经验,但我想在工会中有额外的信息。我想知道如何正确设置它,这是我到目前为止所做的。

typedef struct volunteer{
    int hours;
    int tasksCompleted;
}student;

typedef struct employee{
    float salary;
    int serviceYears;
    int level;
}employee;

typedef union person{
    char firstName[20];
    char familyName[20];
    char telephoneNum[10];
    //employee e;
    //volunteer;
}person;

任何帮助都会很棒。这是我坚持的任务指示。

  

创建一个由常见记录组成的人员记录:名字,姓氏和电话以及志愿者和员工记录之间的联合。确保添加字段以区分员工或志愿者的两种记录类型。

2 个答案:

答案 0 :(得分:2)

我认为你是在思考这个问题:你需要一个代表人的结构。关键部分是

  

"以及志愿者和员工记录之间的联盟。"

typedef enum { employee_person, volunteer_person }  person_type;
typedef struct person{
    char firstName[20];
    char familyName[20];
    char telephoneNum[10];
    person_type type;
    union {
        struct employee employee;
        struct volunteer volunteer;
    };
}person;

答案 1 :(得分:0)

这应该按照你的要求行事:

typedef struct volunteer {
    int hours;
    int tasksCompleted;
} student;

typedef struct employee {
    float salary;
    int serviceYears;
    int level;
} employee;

struct person {
    char firstName[20];
    char familyName[20];
    char telephoneNum[10]; 
    bool is_employee;
    union {
        employee e;
        student s;
    } info;
} person;