0

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

 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(...);

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

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

1 回答 1

1

尝试:

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

或许:

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

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

于 2012-05-13T21:16:14.520 回答