本文介绍了如何使用联合在 1 个 C 数组中存储 2 个不同的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个数组来存储 2 种类型的 C 结构 - Employee 及其子",Manager.我创建了一个联合 Person 来保存它们中的任何一个,然后尝试用它创建一个数组,但它不起作用.我怎样才能让这样的数组工作?相关代码如下.

I would like to create one array to store 2 types of C structs - Employee, and its 'child', Manager. I created a union Person to hold either of them and then tried creating an array with it, but it doesn't work. How can I get such an array to work? The relevant code is below.

 typedef struct {
    char name[20];
    double salary;
    } Employee;

//Manager struct inheriting from employee struct
typedef struct {
    Employee employee;
    int bonus;
} Manager;

typedef union{
       Employee e;
       Manager m;
      } Person;
Manager boss;
Employee harry ;
Employee tommy;
Person staff[];

int main(void)
{
...
boss = newManager(...);
  harry = newEmployee(...);
  tommy = newEmployee(...);

我无法让下一行工作,我尝试了很多东西.

I couldn't get the next line to work, I tried many things.

  staff[3] = {boss, harry, tommy};

推荐答案

尝试:

staff[0].manager = boss;
staff[1].employee = harry;
/* ... */

或者:

Person staff [] = {
    {.manager = boss},
    {.employee = harry},
    /* ... */
};

但问问自己:你以后怎么知道staff[x]是经理还是单纯的员工?

But ask yourself: how will you know later if staff[x] is a manager or a mere employee ?

这篇关于如何使用联合在 1 个 C 数组中存储 2 个不同的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:38