1

Cで継承をシミュレートしていますが、正確な方法がわかりません。EmployeeとDirectorの2つの構造体を作成しました。ここで、DirectorはEmployeeから「継承」することになっています。通常の従業員と取締役の両方を保持できるアレイを作成するにはどうすればよいですか?これは機能しませんでした:

Employee workers[3]

以下は、Director構造体のコードです。

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

4 に答える 4

8

ディレクターunionまたは従業員のいずれかを含むことができるものと、union使用している部分を示すフラグを作成します。union次に、そのタイプの配列を宣言します。

于 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

Employee へのポインターの配列を作成できます。従業員の長さが 64 バイトであるとしましょう。3 つの配列を作成すると、その配列の長さは 192 バイトになり、3 つのディレクターの配列が必要な場合、構造体ごとに 2 バイト余分にかかるため、配列全体は次のようになります。長さは 198 バイトであり、それが配列を思い通りにできない原因です。従業員へのポインターとして配列を作成する場合、それは配列に含まれるものであり、ポインターのみであるため、4 バイトの 3 つのスペース = 12 バイトになり、ポインターは常に同じサイズであるため、ポインターを格納できます。さまざまなサイズの構造。考慮すべき点は次のとおりです。

  • 各アイテムは参照解除する必要があります。
  • 各アイテム (malloc) に対して動的メモリを要求する必要があります。そうしないと、関数が終了したときにアイテムが失われます。
  • メモリが不要になったら、十分に注意して解放してください。
  • 逆参照する前にポインターが null でないことを確認してください。そうしないと、プログラムがクラッシュします。

これが役に立つことを願っています、頑張ってください!

于 2012-05-11T00:52:51.523 に答える