まとめ:図形の階層構造
CoddyのCジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 32/61。
チャレンジ
簡単コンポジションによる継承の力を示す、完全な図形階層を構築しましょう。任意の具体的な図形が継承できる基底の Shape 型を作成し、次にそれを拡張する Rect を構築します。
コードを3つのファイルに分けて整理します。
shape.h: インクルードガードを使用して struct 階層を定義します。単一のcolorfield(整数)を持つShapestruct を作成します。次に、Shapeを first member として埋め込み、widthとheightの field(どちらも整数)を追加したRectstruct を定義します。Shape*と新しい color value を takesset_colorと、Rect*を takesprint_rectの2つの function を Declare します。shape.c: both function を Implement します。set_colorfunction は base type と連携します。任意の shape の color を変更します。print_rectfunction は、継承した color を含む rectangle の all information を display します。main.c:Rectを Create し、its all field を initialize します。次に、rectangle をShape*に cast してset_colorを Call することで、upcasting を示します。最後に rectangle を print して、base type pointer を通じて color が change されたことを確認します。
4つの input を受け取ります。rectangle の width、その height、initial color、そして generic function を通じて設定する new color です。
main file で initial value を使用して rectangle を Create し、set_color を使って color を new value に change します(Rect* を Shape* に cast することを忘れないでください)。最後に print_rect を Call して result を display します。
出力は次のようになります。
Width: 10
Height: 5
Color: 7ここで、10 は width、5 は height、7 は updated color(initial color ではありません)です。ここでの key insight は、set_color が rectangle について何も知らないということです。これは Shape とのみ連携します。しかし、first member rule と upcasting によって、rectangle の color はこの generic function を通じて変更されます。
自分で試してみよう
#include <stdio.h>
#include "shape.h"
int main() {
int width, height, initial_color, new_color;
scanf("%d", &width);
scanf("%d", &height);
scanf("%d", &initial_color);
scanf("%d", &new_color);
// TODO: Rect を作成し、すべてのフィールドを初期化する
// (width、height、および埋め込まれた Shape の color を initial_color で)
// TODO: 矩形を Shape* にキャストして set_color を呼び出す
// 色を new_color に変更する
// TODO: print_rect を呼び出して結果を表示する
return 0;
}
オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: Cオンラインコンパイラ