1

I'm simulating inheritance in C, but not sure the exact way to go. I created 2 structs, Employee and Director, where Director is supposed to 'inherit' from Employee. How do I create an array that will be able to hold both regular Employees and Directors? This did not work:

Employee workers[3]

Below is my code for the Director struct:

typedef struct {
    Employee employee;   
    int bonus;
} Director;
4

4 回答 4

8

Make an union that can contain either Directors or Employees, and a flag stating which part of the union you're using. Then declare an array of that union type.

于 2012-05-11T00:33:59.067 回答
3

You are missing one crucial part - a flag by which you are going to distinguish directors from employees at runtime; this flag goes into struct Employee.

Now you can declare an array of pointers to Employee (it cannot be an array of Employee because directors are not going to fit). You can cast a pointer to Director back to Employee, because the pointer to the struct is always the same as the pointer to its first member.

于 2012-05-11T00:37:39.910 回答
2

You... can't, at least, not like that. Even if it were allowed, what would happen? From what I can tell, sizeof(Employee) != sizeof(Director), so how should the memory be allocated? What happens if I grab an Employee from the array and attempt to access the employee field of a Director object? It just won't work, and for good reason.

You can however use a union as a type which can hold either an Employee or a Director and create an array of those.

于 2012-05-11T00:34:34.900 回答
0

You could make an array of pointers to Employee. Let's say that Employee is 64 bytes long, so if you create an array of 3 that array would be 192 bytes long, and if you would need an array of three Director that would be 2 extra bytes per struct, so your whole array would be 198 bytes long and that is the cause that you can't have the array as you want it. If you create the array as pointers to Employee, that's what the array will contain, pointers only, so it would be three spaces of 4 bytes = 12 bytes, and as the pointer always is the same size you will be able to store pointers to structures of different sizes. You will only have to take some considerations:

  • Each item will need to be de-referenced.
  • You'll need to ask for some dynamic memory for each item (malloc) or your items will be lost when the function ends.
  • Be very careful to free that memory when you don't need it anymore.
  • Verify that the pointer isn't null before de-referencing it or your program will crash.

I hope this is useful, good luck!

于 2012-05-11T00:52:51.523 回答