Menu
Coddy logo textTech

まとめ:図形の階層構造

CoddyのCジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 32/61。

challenge icon

チャレンジ

簡単

コンポジションによる継承の力を示す、完全な図形階層を構築しましょう。任意の具体的な図形が継承できる基底の Shape 型を作成し、次にそれを拡張する Rect を構築します。

コードを3つのファイルに分けて整理します。

  • shape.h: インクルードガードを使用して struct 階層を定義します。単一の color field(整数)を持つ Shape struct を作成します。次に、Shape を first member として埋め込み、widthheight の field(どちらも整数)を追加した Rect struct を定義します。Shape* と新しい color value を takes set_color と、Rect* を takes print_rect の2つの function を Declare します。
  • shape.c: both function を Implement します。set_color function は base type と連携します。任意の shape の color を変更します。print_rect function は、継承した 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、その heightinitial 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オンラインコンパイラ